Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find key in JavaScript Object when his depth is unknown?

If I have an javascript object like this: {a : { b: { c: { ... }}}}, how can I find if there is an 'x' key in the object and what it's value ?

like image 233
Hitman_99 Avatar asked Dec 21 '22 08:12

Hitman_99


2 Answers

So long as their is no fear of cyclic references you could do the following

function findX(obj) { 
  var val = obj['x'];
  if (val !== undefined) {
    return val;
  }
  for (var name in obj) {
    var result = findX(obj[name]);
    if (result !== undefined) {
      return result;
    }
  }
  return undefined;
}

Note: This will search for the property 'x' directly in this object or it's prototype chain. If you specifically want to limit the search to this object you can do so doing the following

if (obj.hasOwnProperty('x')) {
  return obj['x'];
}

And repeating for pattern for the recursive calls to findX

like image 77
JaredPar Avatar answered Dec 24 '22 02:12

JaredPar


function hasKey(obj,key){
    if(key in obj)
        return true;
    for(var i in obj)
        if(hasKey(obj[i],key))
            return true;
    return false;
}

ex:

alert(hasKey({a:{b:{c:{d:{e:{f:{g:{h:{i:{}}}}}}}}}},'i'));
like image 44
gion_13 Avatar answered Dec 24 '22 02:12

gion_13