Search a value inside complex object

时间:2015-09-14 15:33:38

标签: javascript

I have a complex object with nested values. Values could be strings, arrays, arrays of objects or null objects. Something like this:

{
foo:'a',
bar:'b',
otherthings : [{yep:'0',yuk:'yoyo0'},{yep:'1',yuk:'yoyo1'}],
foobar : 'yup',
value: null
}

What is the fastest way to check if a value (e.g. yoyo1) exists somewhere in the object? Is there a Javascript built-in function?

4 个答案:

答案 0 :(得分:2)

Regex Solution

var myObject = {
    foo: 'a',
    bar: 'b',
    otherthings: [{
        yep: '0',
        yuk: 'yoyo0'
    }, {
        yep: '1',
        yuk: 'yoyo1'
    }],
    foobar: 'yup',
    value: null
};

var myStringObject = JSON.stringify(myObject);
var matches = myStringObject.match('yep'); //replace yep with your search query

demo

答案 1 :(得分:2)

一些简短的迭代:



git branch -d `git branch --merged`




答案 2 :(得分:1)

var jsonStr = JSON.stringify(myJSON);
return jsonStr.indexOf(':"yolo1"') !== -1;

This only works if you want to know if it exists (not where it is). It may also not be the most performant.

答案 3 :(得分:1)

Another solution:

 function findInObject(obj, comparedObj){
     return Object.keys(obj).some(function(key){
         var value = obj[key];

         if (!value) {
           return false;
         }

         if (typeof value === "string") {
            return value === comparedObj;
         }

         if (value instanceof Array) {
            return value.some(function(e){ 
                return (typeof value === "string" && e === comparedObj) || 
                       findInObject(e, comparedObj);
            });
         }

         return findInObject(value, comparedObj);
    });  
}