I was wondering if it's possible to access a value inside a nested object with just one string. Supose I have an object like this:
skill: {
skillDetails: {
developerDetails: {
developerName: "mr. developer"
}
}
}
Is there a way I can do something like this, to get the value via a "JSON path": skill["skillDetails.developerDetails.developerName"] ?
The reason I ask this is because I'm trying to pass the key & object into a function (that I can't modify) that essentially returns object[key]
not sure if this possible so I thought I'd ask you guys for some advice.
Thanks!
There is no "built in" method, however a simple solution to this (that doesn't require a third party library) can be achieved via split() and reduce() as follows:
var skill = {
skillDetails: {
developerDetails: {
developerName: "mr. developer"
}
}
}
var path = "skillDetails.developerDetails.developerName";
var value = path
.split('.') // Split path into parts by '.'
.reduce((obj, part) => obj ? obj[part] : undefined, skill); // Extract value via reduction
console.log(value)
Unfortunately there's no quick built-in method to accomplish this -- you'll need a helper function.
lodash supports this using _.get(obj, property).
From the docs:
var object = { 'a': [{ 'b': { 'c': 3 } }] };
_.get(object, 'a[0].b.c');
// → 3
_.get(object, ['a', '0', 'b', 'c']);
// → 3
_.get(object, 'a.b.c', 'default');
// → 'default'
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