在 Javascript 中的对象数组中查找值

2022-08-29 22:43:06

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

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

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


答案 1

查找数组元素:

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

let obj = arr.find(o => o.name === 'string 1');

console.log(obj);

替换数组元素:

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

let obj = arr.find((o, i) => {
    if (o.name === 'string 1') {
        arr[i] = { name: 'new string', value: 'this', other: 'that' };
        return true; // stop searching
    }
});

console.log(arr);

答案 2

您可以遍历数组并测试该属性:

function search(nameKey, myArray){
    for (var i=0; i < myArray.length; i++) {
        if (myArray[i].name === nameKey) {
            return myArray[i];
        }
    }
}

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

var resultObject = search("string 1", array);