且构网

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

迭代嵌套的JavaScript对象

更新时间:2023-01-17 19:41:40

您可以创建这样的递归函数来对汽车进行深度优先遍历 object。

You can create a recursive function like this to do a depth-first traversal of the cars object.

var findObjectByLabel = function(obj, label) {
    if(obj.label === label) { return obj; }
    for(var i in obj) {
        if(obj.hasOwnProperty(i)){
            var foundLabel = findObjectByLabel(obj[i], label);
            if(foundLabel) { return foundLabel; }
        }
    }
    return null;
};

可以像这样调用

findObjectByLabel(car, "Chevrolet");