遍历对象以返回值

时间:2020-08-17 15:05:20

标签: javascript arrays object traversal

我有一个要搜索的值。我想将要搜索的术语与rc = dev_open(inode, file);的值匹配,并返回与同一对象关联的dev_open的键的值。

这是一个示例对象:

key

假设我要查找name{ "test1": { "functions": { "function1": { "inputs": [ { "key": "key1", "name": "name1" }, { "key": "key2", "name": "name3" }, { "key": "key3", "name": "name3" } ] }, "function2": { "inputs": [ { "key": "key4", "name": "name4" }, { "key": "key5", "name": "name5" }, { "key": "key6", "name": "name6" } ] } } } } 的输入的name。我将如何在javascript中实现这一目标?

1 个答案:

答案 0 :(得分:1)

您只需要迭代"inputs"数组内的各个对象,并检查key属性是否为“ key4”

var inputs = []; // you would have to get the individual lists
inputs.forEach(function (input) {
    if (input['key'] === 'key4') {
        // do something with input['name'];
    }
});

最佳地,您将创建一个函数,该函数返回input['name']