0

i have objects which have hold x amounts of nested objects:

let obj = {
 nestedObject: {
  key: value
 }
}

or

let obj2 = {
 nestedObject2: {
  nestedObject3: {
   key2: value2 
  }
 }
}

etc.

Getting the values of both those objects is not that difficult:

obj.nestedObject.key 
obj['nestedObject']['key]

or

obj2.nestedObject2.nestedObject3.key2
obj2['nestedObject2']['nestedObject3']['key2']

This should happen dynamically though which is what I don't know how to achieve. I get random objects with the structure above and also a string which tells me where to find the values. For obj2 in the example above I would get the string

"nestedObject2.nestedObject3.key2"

How do I use this information to get the proper value? The two strategies above don't work anymore and something easy like

obj2['nestedObject2.nestedObject3.key2']

doesn't work unfortunately.

M4V3N
  • 600
  • 6
  • 21

1 Answers1

1

You can split the string by the delimiter of a period character, and then reduce to find the appropriate property, going down a level on every iteration.

str.split(".").reduce((a, v) => (a = a[v], a), parent_object);

let o = {
    nestedObject2: {
      nestedObject3: {
        key2: "a key"
      }
    }
  },
  str = "nestedObject2.nestedObject3.key2";

let ref = str.split(".").reduce((a, v) => (a = a[v], a), o);

console.log(ref);
zfrisch
  • 8,474
  • 1
  • 22
  • 34