Home > Software design >  Get value of the key in deeply nested object
Get value of the key in deeply nested object

Time:01-29

Let's say I have input object like this one:

const obj = {
  deep: {
    someKey: 'someValue1!',
    veryDeep: {
      someOtherKey: 'someOtherValue'
    }
  },
  deep2: {
    aa: 'bba'
  }
}

I want to write a function that will take this object as first argument and key string as second argument. Then it's gonna loop through obj with recursion and find the value and return it. So if I name this function getObjectValueOfKey it will be called like this: getObjectValueOfKey(obj, 'aa') and it will return 'bba'.

I think I'm close with this code:

const getObjectValueOfKey = (obj, key) => {
  const keys = Object.keys(obj)
  for (let currKey of keys) {
    if (typeof obj[currKey] === 'object') {
      getObjectValueOfKey(obj[currKey], key)
    }
    if (currKey === key) {
      return obj[key]
    }
  }
}

const res = getObjectValueOfKey(obj, 'aa')
console.log('res', res)

but for some unknown to me reasons res is undefined.

CodePudding user response:

you were pretty close, the recursion was good but the problem is related with what all the paths in your code doesn't return, actually the only path that return is when you found the key in the first level of the object, after you made the recursion and found the result but nothing was returned, the code reach the end the of function and javascript return by default undefined if any return is not found, to solve the problem a decide to store the results found in the recursion in a variable and return that value at the end of the function.

const getObjectValueOfKey = (obj, key, found) => {

  const keys = Object.keys(obj);
  let result = undefined;
  result ||= found;
  for (let currKey of keys) {
    if (typeof obj[currKey] === "object") {
      result ||= getObjectValueOfKey(obj[currKey], key, result);
    }
    if (currKey === key) {
      return obj[key];
    }
  }
  return result;
};

const res = getObjectValueOfKey(obj, "aa", undefined);
console.log("res", res);
  •  Tags:  
  • Related