我知道以前也有人问过类似的问题,但这个问题有点不同。我有一个未命名对象的数组,其中包含一个命名对象的数组,我需要得到其中“name”为“string 1”的对象。下面是一个示例数组。

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

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


当前回答

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

    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'}
);

其他回答

使用findWhere方法:

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

使用简单的for循环:

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

如果可以,也就是说,如果您的浏览器支持,请使用Array。过滤器,它更简洁:

var result = array.filter(function (obj) {
  return obj.name === "string 1";
})[0];

一行回答。 你可以使用过滤函数来得到结果。

Var数组= [ {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]);

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

array[array.findIndex(x => x.name == 'string 1')]

您是否在对象列表中查找跨项目的通用搜索(筛选器)而不指定项目键

输入

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');