Itsik Mauyhas Itsik Mauyhas - 2 months ago 5
JSON Question

Javascript - retrive a value by key, including nested object

I am trying to write a function that will retrieve a value by key, including searching in nested objects.

Here is as far as I got:

function getByKey (obj, key) {
if(obj.hasOwnProperty(key)){
return obj[key];
}else{
for(var prop in obj){
if(typeof prop == "object" && prop !== null){
if(prop.hasOwnProperty(key)){
return prop[key];
}else{
return iterate(prop, key);
}
}
}
}


}

If someone have this function ready and working or can fix my it will be great. If someone knows Underscore function that can do this it will be great.

Answer

You could use an iterative and recursive style to search for the property of an object.

function getByKey(obj, key) {
    function iter(o) {
        if (o !== null && typeof o === 'object') {
            if (key in o) {
                value = o[key];
                return true;
            }
            return Object.keys(o).some(function (k) {
                return iter(o[k]);
            });
        }
    }

    var value;
    iter(obj);
    return value;
}

var o = { a: 1, b: { c: 3, d: 4, e: { f: 5, g: 6 } } }

console.log(getByKey(o, 'f')); // 5
console.log(getByKey(o, 'b')); // { c: ... }
console.log(getByKey(o, 'd')); // 4
console.log(getByKey(o, 'q')); // undefined
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments