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

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

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


当前回答

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

输入

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

其他回答

另一种方法(帮助@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'};

使用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

查找数组元素:

令arr = [ {name:"string 1", value:"this", other: "that"}, {name:"string 2", value:"this", other: "that"} ]; 令obj = arr。Find (o => o.name === 'string 1'); console.log (obj);


替换数组元素:

令arr = [ {name:"string 1", value:"this", other: "that"}, {name:"string 2", value:"this", other: "that"} ]; 令obj = arr。Find ((o, i) => { If (o.name === 'string 1') { Arr [i] = {name: '新字符串',value: 'this', other: 'that'}; 返回true;//停止搜索 } }); console.log (arr);

这个答案适用于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('这里我们看到highlightdays是什么',obj.css); let dayCss = obj.css;

使用简单的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];