4

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 ?

1
  • Hmmm, and what would you want to do if there are multiple x keys? E.g. {a:{x:1}, b:{x:2}} Commented Sep 15, 2011 at 21:07

2 Answers 2

8

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

Sign up to request clarification or add additional context in comments.

2 Comments

Note that this will also search the prototype chain. If that's not desired, throw a couple of hasOwnProperty calls at it.
@T.J. Crowder searching the prototype was my intent here as it seemed the OP just wanted to know if 'x' existed anywhere. I will update my answer to make that explicit
3
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'));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.