按键查找和检索对象值,包括嵌套对象 [英] Find and retrive object value by key, include nested objects

查看:107
本文介绍了按键查找和检索对象值,包括嵌套对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过 key 找到而不知道对象,包含嵌套对象,所以函数将获取一个键和一个对象并返回值或未定义。
这是我的函数:

I am trying to find a value by key without knowing the object, include nested object, so the function will get a key and a object and return the value or undefined. This is my function:

/* Iterate over object and include sub objects */

function iterate (obj, key) {

    for (var property in obj) {
        if (obj.hasOwnProperty(property)) {
            //in case it is an object
            if (typeof obj[property] == "object") {
                if (obj.hasOwnProperty(key)) {
                    return obj[key]; //return the value 
                }
            }
            else {
                iterate(obj[property]);
            }
        }   
    }

    return undefined;
}

我打电话给返回在一个循环中,所以它会更有效(希望如此......)。

I call return inside a loop so it will be more efficient(hope so...).

1.是否有人准备好这个功能?这个不起作用。

1.is anyone have this function ready? this one does not work.

2.有人知道要改变什么才能使它有效吗?

2.someone knows what to change to make it work?

任何帮助,包括 angular.js 功能都会很棒。

Any help, including angular.js functions will be great.

谢谢。

推荐答案

你反转了一点,你忘了将第二个参数传递给递归函数调用。此外,在这种情况下,不需要返回 undefined ,因为这是默认值。

You reversed things a bit and you forgot to pass the second parameter to the recursive function call. Also, in this case there's no need to return undefined, because that is the default.

function iterate (obj, key) {
    var result;

    for (var property in obj) {
        if (obj.hasOwnProperty(property)) {
            // in case it is an object
            if (typeof obj[property] === "object") {
                result = iterate(obj[property], key);

                if (typeof result !== "undefined") {
                    return result;
                }
            }
            else if (property === key) {
                return obj[key]; // returns the value
            }
        }   
    }
}

编辑:实际上,我们应该在检查值是否为可迭代对象之前检查属性是否等于键,如果我们要查找值为宾语。感谢@Catinodeh!

Actually, we should check if the property is equal to the key BEFORE checking if the value is an iterable object, in the case where we are looking for a key whose value is an object. Thanks to @Catinodeh!

function iterate (obj, key) {
    var result;

    for (var property in obj) {
        if (obj.hasOwnProperty(property)) {
            if (property === key) {
                return obj[key]; // returns the value
            }
            else if (typeof obj[property] === "object") {
                // in case it is an object
                result = iterate(obj[property], key);

                if (typeof result !== "undefined") {
                    return result;
                }
            }
        }   
    }
}

这篇关于按键查找和检索对象值,包括嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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