1

If I have an object with nested properties. Is there a function that will search all properties, and the properties with values that are other objects (which also have their own properties) and so forth?

Example object:

const user = { 
    id: 101, 
    email: 'help@stack.com', 
    info: { 
        name: 'Please', 
        address: {
            state: 'WX' 
        }
    }
}

In the object above is there a way I could simply call something like

console.log(findProp(user, 'state'));
console.log(findProp(user, 'id'));
  • You might consider using something like what's describe in this question: [Accessing nested JavaScript objects with string key](https://stackoverflow.com/q/6491463) – Heretic Monkey Jun 07 '18 at 20:01
  • I think this one might answer your question though: [How to get the key value from nested object](https://stackoverflow.com/q/38083288) – Heretic Monkey Jun 07 '18 at 20:02
  • @MikeMcCaughan The problem with that article, is all the answers are providing the direct location. Rather than simply requesting it anywhere in the object regardless of how many levels deep. – michaelkazman Jun 07 '18 at 20:10
  • @MikeMcCaughan The second article was exactly what I was looking for. Thank you so much. – michaelkazman Jun 07 '18 at 20:11
  • @PatrickRoberts That post is even better, as I'm using it to find unique properties so there would be no need for it to be in an array – michaelkazman Jun 07 '18 at 20:18

2 Answers2

1

What you need is a recursive function which looks up nested items (Object and Array as well) for the matching key (i also added an array for the lookup):

var user = { id: 101, email: 'help@stack.com', info: {name: 'Please', address: {state: 'WX' }, contacts: [{'phone': '00000000'}, {'email': 'aaa@bbb.ccc'}]}}

function keyFinder(object, key) {
  if(object.hasOwnProperty(key)) return object[key];
  for(let subkey in object) {
    if(!object.hasOwnProperty(subkey) || typeof object[subkey] !== "object") continue;
    let match = keyFinder(object[subkey], key);
    if(match) return match;
  }
  return null;
}

console.log('id', keyFinder(user, 'id'));
console.log('state', keyFinder(user, 'state'));
console.log('phone', keyFinder(user, 'phone'));
console.log('notexisting', keyFinder(user, 'notexisting'));

Object.hasOwnProperty guards against iterating over or retrieving built-in properties.

wiesion
  • 2,349
  • 12
  • 21
0
 function findProp(obj, search) {
   if(key in obj) return obj[key];
   for(const key in obj) {
     if(typeof obj[key] === "object" && obj[key] !== null) {
       const res = findProp(obj[key], search);
       if(res) return res;
     }
   }
}
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151