539

我知道以前有人问过类似的问题,但这个问题有点不同。我有一个未命名对象数组,其中包含一个命名对象数组,我需要获取“名称”为“字符串 1”的对象。这是一个示例数组。

var array = [
    { name:"string 1", value:"this", other: "that" },
    { name:"string 2", value:"this", other: "that" }
];

更新:我应该早点说这个,但是一旦我找到它,我想用一个编辑过的对象替换它。

4

20 回答 20

1174

查找数组元素:

let arr = [
    { name:"string 1", value:"this", other: "that" },
    { name:"string 2", value:"this", other: "that" }
];

let obj = arr.find(o => o.name === 'string 1');

console.log(obj);


替换数组元素:

let arr = [
    { name:"string 1", value:"this", other: "that" },
    { name:"string 2", value:"this", other: "that" }
];

let obj = arr.find((o, i) => {
    if (o.name === 'string 1') {
        arr[i] = { name: 'new string', value: 'this', other: 'that' };
        return true; // stop searching
    }
});

console.log(arr);

于 2012-09-17T15:24:48.013 回答
307

您可以遍历数组并测试该属性:

function search(nameKey, myArray){
    for (var i=0; i < myArray.length; i++) {
        if (myArray[i].name === nameKey) {
            return myArray[i];
        }
    }
}

var array = [
    { name:"string 1", value:"this", other: "that" },
    { name:"string 2", value:"this", other: "that" }
];

var resultObject = search("string 1", array);
于 2012-09-17T15:23:36.437 回答
202

ES6中你可以Array.prototype.find(predicate, thisArg?)这样使用:

array.find(x => x.name === 'string 1')

http://exploringjs.com/es6/ch_arrays.html#_searching-for-array-elements https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/find

然后替换所述对象(并使用另一种很酷的ES6方法fill),您可以执行以下操作:

let obj = array.find(x => x.name === 'string 1');
let index = array.indexOf(obj);
array.fill(obj.name='some new string', index, index++);
于 2016-07-21T09:34:37.427 回答
75

根据 ECMAScript 6,您可以使用该findIndex函数。

array[array.findIndex(x => x.name == 'string 1')]
于 2017-05-18T12:56:03.417 回答
60
var array = [
    { name:"string 1", value:"this", other: "that" },
    { name:"string 2", value:"this", other: "that" }
];

var foundValue = array.filter(obj=>obj.name==='string 1');

console.log(foundValue);
于 2017-12-13T10:30:31.163 回答
58

考虑到您有以下代码段:

var array = [
    { name:"string 1", value:"this", other: "that" },
    { name:"string 2", value:"this", other: "that" }
];

您可以使用以下功能来搜索项目

const search = what => array.find(element => element.name === what);

您可以检查是否找到了该项目。

if (search("string 1")) {
    console.log(search.value, search.other);
} else {
    console.log('No result found');
}
于 2018-02-10T08:52:48.997 回答
25

使用 foreach:

let itemYouWant = null;
array.forEach((item) => {
    if (item.name === 'string 1') {
        itemYouWant = item;
    }
});
console.log(itemYouWant);

或者使用地图更好:

const itemYouWant = array.map((item) => {
    if (item.name === 'string 1') {
        return item;
    }
    return null;
});
console.log(itemYouWant);
于 2017-05-04T09:19:40.673 回答
22

要么使用一个简单的for循环:

var result = null;
for (var i = 0; i < array.length; i++) { 
  if (array[i].name === "string 1") { 
    result = array[i];
    break;
  } 
}

或者,如果可以,也就是说,如果您的浏览器支持它,请使用Array.filter,这更简洁:

var result = array.filter(function (obj) {
  return obj.name === "string 1";
})[0];
于 2012-09-17T15:24:24.733 回答
22

使用underscore.jsfindWhere 方法:

var array = [
    { name:"string 1", value:"this", other: "that" },
    { name:"string 2", value:"this", other: "that" }
];


var result = _.findWhere(array, {name: 'string 1'});

console.log(result.name);

JSFIDDLE中看到这个

于 2015-07-31T14:16:29.157 回答
19

一行回答。您可以使用过滤功能来获得结果。

var array = [
    { name:"string 1", value:"this", other: "that" },
    { name:"string 2", value:"this", other: "that" }
];

console.log(array.filter(function(arr){return arr.name == 'string 1'})[0]);

于 2017-11-09T04:43:20.083 回答
13

新答案

我将 prop 添加为参数,以使其更通用和可重用

/**
 * Represents a search trough an array.
 * @function search
 * @param {Array} array - The array you wanna search trough
 * @param {string} key - The key to search for
 * @param {string} [prop] - The property name to find it in
 */

function search(array, key, prop){
    // Optional, but fallback to key['name'] if not selected
    prop = (typeof prop === 'undefined') ? 'name' : prop;    

    for (var i=0; i < array.length; i++) {
        if (array[i][prop] === key) {
            return array[i];
        }
    }
}

用法:

var array = [
    { 
        name:'string 1', 
        value:'this', 
        other: 'that' 
    },
    { 
        name:'string 2', 
        value:'this', 
        other: 'that' 
    }
];

search(array, 'string 1');
// or for other cases where the prop isn't 'name'
// ex: prop name id
search(array, 'string 1', 'id');

摩卡测试:

var assert = require('chai').assert;

describe('Search', function() {
    var testArray = [
        { 
            name: 'string 1', 
            value: 'this', 
            other: 'that' 
        },
        { 
            name: 'string 2', 
            value: 'new', 
            other: 'that' 
        }
    ];

    it('should return the object that match the search', function () {
        var name1 = search(testArray, 'string 1');
        var name2 = search(testArray, 'string 2');

        assert.equal(name1, testArray[0]);
        assert.equal(name2, testArray[1]);

        var value1 = search(testArray, 'this', 'value');
        var value2 = search(testArray, 'new', 'value');

        assert.equal(value1, testArray[0]);
        assert.equal(value2, testArray[1]);
    });

    it('should return undefined becuase non of the objects in the array have that value', function () {
        var findNonExistingObj = search(testArray, 'string 3');

        assert.equal(findNonExistingObj, undefined);
    });

    it('should return undefined becuase our array of objects dont have ids', function () {
        var findById = search(testArray, 'string 1', 'id');

        assert.equal(findById, undefined);
    });
});

测试结果:

Search
    ✓ should return the object that match the search
    ✓ should return undefined becuase non of the objects in the array have that value
    ✓ should return undefined becuase our array of objects dont have ids


  3 passing (12ms)

旧答案 - 由于不良做法而被删除

如果您想了解更多为什么这是不好的做法,请参阅这篇文章:

为什么扩展本机对象是一种不好的做法?

进行数组搜索的原型版本:

Array.prototype.search = function(key, prop){
    for (var i=0; i < this.length; i++) {
        if (this[i][prop] === key) {
            return this[i];
        }
    }
}

用法:

var array = [
    { name:'string 1', value:'this', other: 'that' },
    { name:'string 2', value:'this', other: 'that' }
];

array.search('string 1', 'name');

于 2015-10-13T08:05:31.350 回答
7

你可以用一个简单的循环来做到这一点:

var obj = null;    
for (var i = 0; i < array.length; i++) {
    if (array[i].name == "string 1") {
        obj = array[i];
        break;
    }
}
于 2012-09-17T15:21:18.717 回答
4

另一种方法(帮助@NullUserException 和@Wexoni 的评论)是在数组中检索对象的索引,然后从那里开始:

var index = array.map(function(obj){ return obj.name; }).indexOf('name-I-am-looking-for');
// Then we can access it to do whatever we want
array[index] = {name: 'newName', value: 'that', other: 'rocks'};
于 2016-06-09T20:53:47.960 回答
3

与以前的答案类似,我使用了以下内容:

    Array.prototype.getIemtByParam = function(paramPair) {
      var key = Object.keys(paramPair)[0];
      return this.find(function(item){return ((item[key] == paramPair[key]) ? true: false)});
    }

用法:

myArray.getIemtByParam(
    {name: 'Sasha'}
);
于 2015-11-20T11:35:51.627 回答
2

这是搜索和替换的解决方案

function searchAndUpdate(name,replace){
    var obj = array.filter(function ( obj ) {
        return obj.name === name;
    })[0];
    obj.name = replace;
}

searchAndUpdate("string 2","New String 2");
于 2014-06-17T12:05:35.833 回答
2

您是否在对象列表中的项目中寻找通用搜索(过滤器)而不指定项目键

输入

var productList = [{category: 'Sporting Goods', price: '$49.99', stocked: true, name: 'Football'}, {category: 'Sporting Goods', price: '$9.99', stocked: true, name: 'Baseball'}, {category: 'Sporting Goods', price: '$29.99', stocked: false, name: 'Basketball'}, {category: 'Electronics', price: '$99.99', stocked: true, name: 'iPod Touch'}, {category: 'Electronics', price: '$399.99', stocked: false, name: 'iPhone 5'}, {category: 'Electronics', price: '$199.99', stocked: true, name: 'Nexus 7'}]
function customFilter(objList, text){
if(undefined === text || text === '' ) return objList;
return objList.filter(product => {
    let flag;
    for(let prop in product){
        flag = false;
        flag = product[prop].toString().indexOf(text) > -1;
        if(flag)
        break;
    }
return flag;
});}

执行

customFilter(productList, '$9');

在此处输入图像描述

于 2017-03-19T19:56:20.043 回答
1

如果您使用 jQuery,请尝试 $.grep()。

http://api.jquery.com/jquery.grep/

于 2016-05-27T18:16:09.930 回答
0

您可以使用来自 npm的查询对象。您可以使用过滤器搜索对象数组。

const queryable = require('query-objects');

const users = [
    {
      firstName: 'George',
      lastName: 'Eracleous',
      age: 28
    },
    {
      firstName: 'Erica',
      lastName: 'Archer',
      age: 50
    },
    {
      firstName: 'Leo',
      lastName: 'Andrews',
      age: 20
    }
];

const filters = [
    {
      field: 'age',
      value: 30,
      operator: 'lt'
    },
    {
      field: 'firstName',
      value: 'Erica',
      operator: 'equals'
    }
];

// Filter all users that are less than 30 years old AND their first name is Erica
const res = queryable(users).and(filters);

// Filter all users that are less than 30 years old OR their first name is Erica
const res = queryable(users).or(filters);
于 2016-08-05T09:41:06.193 回答
-1
function getValue(){
    for(var i = 0 ; i< array.length; i++){
        var obj = array[i];
        var arr = array["types"];
        for(var j = 0; j<arr.length;j++ ){
            if(arr[j] == "value"){
                return obj;
            }
        }

    }
}
于 2014-12-12T12:07:38.647 回答
-1

这个答案适用于 typescript / Angular 2、4、5+

我在上面的@rujmah 答案的帮助下得到了这个答案。他的回答带来了数组计数......然后找到该值并将其替换为另一个值......

这个答案所做的只是获取可能通过另一个模块/组件在另一个变量中设置的数组名称......在这种情况下,我构建的数组有一个 css 名称,即stay-dates。所以它所做的是提取该名称,然后允许我将其设置为另一个变量并像这样使用它。就我而言,它是一个 html css 类。

let obj = this.highlightDays.find(x => x.css); let index = this.highlightDays.indexOf(obj); console.log('here we see what hightlightdays is ', obj.css); let dayCss = obj.css;

于 2017-07-27T16:08:28.030 回答