Home > Mobile >  How to get to child-child objects using bracket notation?
How to get to child-child objects using bracket notation?

Time:08-09

My Object looks like this:

let obj = {
  foo: {
    bar: 'value'
  }
}

I want to access the value of bar via the string 'foo.bar'.

But obj['foo.bar'] is not working.

How can I do it?

CodePudding user response:

Each property must be in its own bracket.

obj['foo']['bar']; // 'value'

So if you have a string 'foo.bar', you must split that string into parts.

let obj = {
  foo: {
    bar: 'value'
  }
}

let paths = 'foo.bar'.split('.');

let value = paths.reduce((acc, path) => {
  acc = acc[path];
  return acc;
},obj)
  • Related