且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

通过属性名称递归搜索对象中的值

更新时间:2023-01-16 19:11:36

您可以使用 Array#some .

You could use Object.keys and iterate with Array#some.

function findVal(object, key) {
    var value;
    Object.keys(object).some(function(k) {
        if (k === key) {
            value = object[k];
            return true;
        }
        if (object[k] && typeof object[k] === 'object') {
            value = findVal(object[k], key);
            return value !== undefined;
        }
    });
    return value;
}

var object =  { photo: { progress: 20 }};
console.log(findVal(object, 'progress'));