在 Javascript 中的对象数组中查找值 [英] Find a value in an array of objects in Javascript

查看:27
本文介绍了在 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);

这篇关于在 Javascript 中的对象数组中查找值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆