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

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

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


当前回答

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

其他回答

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

在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方法填充),你可以这样做:

let obj = array.find(x => x.name === 'string 1');
let index = array.indexOf(obj);
array.fill(obj.name='some new string', index, index++);

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

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

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

查找数组元素:

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