1

I want to access a JSObject item dynamically:

jsonElement = {
   name:"name",
   subElement {
       subElementName: "nameSubElement",
   }
}

And I have the element as:

//level = "name"
jsonElement[level] -> it works
//level = "subElement.nameSubElement"
jsonElement[level] -> not correct. how to?

The important issue I can't do things like json.subElement.nameSubElement because I just have var level.

mplungjan
  • 169,008
  • 28
  • 173
  • 236
cucuru
  • 3,456
  • 8
  • 40
  • 74
  • http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/ – str Jan 25 '18 at 10:04
  • @mplungjan That is not the [question](https://stackoverflow.com/questions/6491463/accessing-nested-javascript-objects-with-string-key) I marked this as a duplicate of, and it is not what this question is about. Please change the duplicate question. – str Jan 25 '18 at 10:14
  • @mplungjan The questions are totally different. Your suggestion is about using properties in general, my suggestion answers this question: Accessing nested properties based on a *string* path. – str Jan 25 '18 at 10:17
  • Hmm, I think the question is far too vague to assess. So I agree that yours MIGHT answer it too. – mplungjan Jan 25 '18 at 10:19
  • If you read the comment to https://stackoverflow.com/a/48440218/295783 from OP, then I think mine is the one needed. – mplungjan Jan 25 '18 at 10:20
  • @mplungjan I read it as that OP has a *string* and using `split` only works if you know the number of properties beforehand. But anyway, OP should be more specific. – str Jan 25 '18 at 10:22
  • @cucuru, is the `//level = "subElement.nameSubElement"` example not supposed to be `//level = "subElement.subElementName"` ? – mplungjan Jan 25 '18 at 10:24
  • @mplungjan oh yes! Sorry! – cucuru Jan 25 '18 at 10:51
  • @str - so my intuition was correct ;) – mplungjan Jan 25 '18 at 11:02

1 Answers1

2
jsonElement.subElement.subElementName

or

jsonElement["subElement"]["subElementName"]
YounesM
  • 2,279
  • 15
  • 28