Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I access a value inside some nested objects with just a single string?

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!

like image 252
Tim Avatar asked Aug 31 '26 11:08

Tim


2 Answers

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)
like image 64
Dacre Denny Avatar answered Sep 04 '26 03:09

Dacre Denny


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'
like image 40
Elliot B. Avatar answered Sep 04 '26 03:09

Elliot B.