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)
you can do this
function getPropValues(obj, ...keys) {
return keys.reduce((p, c) => {
return p[c]
}, obj)
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With