0

For Example I have this Object structure.

let data = {
  id: 2, 
  content: [
    {foo: "bar1"},
    {foo: "bar2"},
  ]
};

And the only thing I know is this String:

content[0].foo

How can I access the property with this square brackets in the string?

I know that you can access objects like this:

data['content'] // (2) [{…}, {…}]
data['content'][0] // {foo: 'bar1'}

I tried to use something like this data['content[0]'] but this is undefined because here js tries to get the key that has square brackets in it.

I have more complex data structures like this in my project: data.content[0].carousel.images[3].id.

What is the best possible way to access the property only knowing the string to the correct property containing square brackets for the array positions?

anvin
  • 450
  • 2
  • 8
  • 22
  • 1
    Just a side note that `content[0].bar` will give you `undefined`. `content[0]` has no `bar` property in the example. – T.J. Crowder Oct 15 '21 at 09:58
  • 1
    You could use [some library](https://github.com/mariocasciaro/object-path) to access nested props. – Dmitrii Zolotuhin Oct 15 '21 at 10:00
  • Oh yes you are right that was a mistake while writing the question, thanks ill edit it – anvin Oct 15 '21 at 10:01
  • "What is the best possible way to access the property only knowing the string to the correct property containing square brackets for the array positions?" None. There isn't one! – Bekim Bacaj Oct 15 '21 at 10:02
  • I ended up using this: https://www.npmjs.com/package/object-resolve-path – anvin Oct 15 '21 at 10:19

0 Answers0