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

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

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


当前回答

在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++);

其他回答

下面是搜索和替换的解决方案

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

searchAndUpdate("string 2","New String 2");

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

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

你可以循环数组并测试该属性: 函数搜索(nameKey, myArray){ For(令i=0;i < myArray.length;我+ +){ if (myArray[i].name === nameKey) { 返回myArray[我]; } } } Const数组= [ {name:"string 1", value:"this", other: "that"}, {name:"string 2", value:"this", other: "that"} ]; const resultObject = search("string 1",数组); console.log (resultObject)

你可以使用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);

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