Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I dynamically get the value of a nested object property in JavaScript?

Tags:

javascript

Say I have the following object:

let exampleObj = {
   hello: {
      there: {
         friend: 'my friend!',
         neighbor: 'neighbor!',
         world: 'world!'
      }
   }
}

Is there an efficient way I can create a function such as

function getPropValues(obj, ...keys) {
 // ...
}

where if I call getPropValues with the following arguments

const result = getPropValues(exampleObj, 'hello', 'there', 'world');

It would give me the result of exampleObj['hello']['there']['world']?

(i.e. I would expect result to be 'world!' in this case)

like image 761
jknowlesdev Avatar asked Feb 25 '26 07:02

jknowlesdev


2 Answers

you can do this

function getPropValues(obj, ...keys) {
    return keys.reduce((p, c) => {
        return p[c]
    }, obj)
}

like image 102
dasl Avatar answered Feb 28 '26 04:02

dasl


Use Array.prototype.reduce() with Optional chaining ?. as a fallback to undefined for missing properties:

const exampleObj = {
  hello: {
    there: {
      friend: 'my friend!',
      neighbor: 'neighbor!',
      world: 'world!'
    }
  }
};

const getVal = (ob, ...k) => k.reduce((o, k) => o?.[k], ob);

console.log( getVal(exampleObj, "hello", "there", "world") ); // "world!"
console.log( getVal(exampleObj, "hello", "stranger") );       // undefined

Or if you like a dotted string notation:
(Be careful since bug-prone. Properties can also have dots)

const exampleObj = {
  hello: {
    there: {
      friend: 'my friend!',
      neighbor: 'neighbor!',
      world: 'world!'
    }
  }
};

const getVal = (ob, s) => s.split('.').reduce((o, k) => o?.[k], ob);

console.log( getVal(exampleObj, "hello.there.world") ); // "world!"
console.log( getVal(exampleObj, "hello.stranger") );    // undefined
like image 28
Roko C. Buljan Avatar answered Feb 28 '26 04:02

Roko C. Buljan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!