Javascript 在对象中搜索值的键/类型

Javascript 在对象中搜索值的键/类型,javascript,arrays,Javascript,Arrays,我有一个返回对象的递归函数。此对象的深度因输入而异,关键点也取决于输入。在JSON格式中,对象可以如下所示: { a: { b: { c: 3 // Keys with an integer value are the target of the search }, c: 2 } } function search(obj) { for (prop in obj) { if (obj

我有一个返回对象的递归函数。此对象的深度因输入而异,关键点也取决于输入。在JSON格式中,对象可以如下所示:

{
    a: {
        b: {
            c: 3 // Keys with an integer value are the target of the search
        },
        c: 2
    }
}
function search(obj) {
    for (prop in obj) {
        if (obj.hasOwnProperty(prop)) {
            if (prop === "c") {
                 console.log(obj[prop]);    // or whatever you want to do here
            } else if (typeof obj[prop] === "object") {
                search(obj[prop]);
            }
        }
    }
}

如何查找名为c或包含整型值的键?

您可以执行以下操作:

{
    a: {
        b: {
            c: 3 // Keys with an integer value are the target of the search
        },
        c: 2
    }
}
function search(obj) {
    for (prop in obj) {
        if (obj.hasOwnProperty(prop)) {
            if (prop === "c") {
                 console.log(obj[prop]);    // or whatever you want to do here
            } else if (typeof obj[prop] === "object") {
                search(obj[prop]);
            }
        }
    }
}

请参见

Lodash非常适合以下方面:

var val = _(obj).map(function recursive(val, key) {
   if (key === 'c')
       return val;
    else if (typeof val === "object") 
       return _.map(val, recursive);
}).flatten().value();
洛达斯文件:


jsFiddle:

First:在JavaScript中,这不是数组。它是一个对象。如果没有某种形式的迭代,你可能无法进行嵌套,但你不必嵌套任何东西,而是递归地进行。@Pointy用正确的术语更新了问题。@adeneo我没有嵌套就指定了它,因为与此类似的其他几个问题只是给出了嵌套的答案,因为对象的深度是不可变的。我已经编辑了问题,删除了这个。