Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get to child-child objects using bracket notation?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How can I do it?

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading