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

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

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


当前回答

查找数组元素:

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

其他回答

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

你可以用一个简单的循环来实现:

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

你可以循环数组并测试该属性: 函数搜索(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)

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