-3

This is JSON object

{
 "key": "***************",
"****************": {
 "comment": "hello" 
}
"text": "world"
}

I want to return comment field, how?

Andreas
  • 21,535
  • 7
  • 47
  • 56
vazha
  • 3
  • 4

1 Answers1

0

Try item[item.key].comment to access it

Edited based on Stephen Ostermiller comment.

Lets say you have a variable like this:

let item = {
  "key": "someDynamicString",
  "someDynamicString": {
    "comment": "hello" 
  }
  "text": "world"
}

You can access the value of key property by either

item.key

or

item["key"]

both of those will return the value of item.key which is "someDynamicString"

The latter option can be use to access object property which have dynamic key. Let say that "someDynamicString" key is not always "someDynamicString", but dynamically change based on item.key.

You can access that dynamic key with item[item.key] which is equal to item["someDynamicString"] and item.someDynamicString

so whatever the item.key value is, you can always access the second level in json object you asked about.

Furthermore, to access comment property inside the dynamic key: item[item.key].comment

Further explanation: Dynamically access object property using variable

  • [A code-only answer is not high quality](//meta.stackoverflow.com/questions/392712/explaining-entirely-code-based-answers). While this code may be useful, you can improve it by saying why it works, how it works, when it should be used, and what its limitations are. Please [edit] your answer to include explanation and link to relevant documentation. – Stephen Ostermiller Oct 14 '21 at 16:42