Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

54
Views
Get value of the key in deeply nested object

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!