简体   繁体   English

Javascript在JSON对象中递归查找

[英]Javascript find recursively in JSON object

I have the following array: 我有以下数组:

c = ['foo', 'bar'];

and an object 和一个对象

this.foobar = {"foo":{"bar":123}};

How can I search for each of the elements in the array in the JSON object that I have. 如何在我拥有的JSON对象中搜索数组中的每个元素。 It needs to be recursive. 它需要递归。 A PHP version with arrays of what I am trying to do would be something along the lines of: 具有我要执行的操作的数组的PHP版本可能类似于以下内容:

function in_array_recursive($needle, $haystack) { 
    if(in_array($needle, $haystack)) 
        return true; 
    foreach($haystack as $elem) 
        if(is_array($elem) && in_array_recursive($needle, $elem) 
            return true; 
    return false; 
}  

However what I need to do is the same but in JavaScript and instead of arrays I need to use JSON. 但是我需要做的是相同的,但是在JavaScript中,我需要使用JSON而不是数组。

You could do something like the below, which looks for keys that match needle 您可以执行以下操作,查找与针头匹配的键

var foobar = {
    "foo": {
        "whooop" : {
        "bar" : 123
        }
    }
};

function isInArray(needle, haystack) { 
    var foundNeedle = false;

    for (var key in haystack) {

        if (isInArray(needle, haystack[key])) {
            foundNeedle = true;
        }

        if (key == needle) {
            foundNeedle = true
        }
    }

    return foundNeedle;    
}  

var message = "is bar in foobar? result is... " +  isInArray("bar", foobar));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM