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

2022-01-31 00:00:00 arrays javascript

我知道以前有人问过类似的问题,但这个问题有点不同.我有一个未命名对象数组,其中包含一个命名对象数组,我需要获取名称"为字符串 1"的对象.这是一个示例数组.

I know similar questions have been asked before, but this one is a little different. I have an array of unnamed objects, which contain an array of named objects, and I need to get the object where "name" is "string 1". Here is an example array.

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

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

Update: I should have said this earlier, but once I find it, I want to replace it with an edited object.

推荐答案

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

You can loop over the array and test for that property:

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

相关文章