简体   繁体   中英

Fetch value based in that same JSON key value

I have the JSON like

var resultJSON = `{
  "data": {
    "total": 1,
    "list_name": "title",
    "title": {
      "id": 53,
      "name": "Sonu",
      "mobileNo": "6543213456",
      "address": "Greeny Pathway",
      "city": "NewYork",
      "mode": "Weekly",
      "duration": "15",
      "qty": null
    },
    "download": [{
      "time": "16789042",
      "date": "26 - 01 - 2020"
    }]
  }
}`;

I expect the output:

{
  "total": "1",
  "list_name": "title",
  "name": "sonu",
  "mobileno": "6543213456"
}

Here "list_name": "title" is dynamic, sometimes it will come "list_name": "book" , based on that above mentioned response I want to get.

Something like this? I had to fix your invalid JSON

You can make it more clever if you study https://javascript.info/destructuring-assignment in depth

 const resultJSON = `{ "data": { "total": 1, "list_name": "title", "title": { "id": 53, "name": "Sonu", "mobileNo": "6543213456", "address": "Greeny Pathway", "city": "NewYork", "mode": "Weekly", "duration": "15", "qty": null }, "download": [{ "time": "16789042", "date": "26-01-2020" }] } }` const data = JSON.parse(resultJSON).data const content = data[data.list_name]; let newObj = {} newObj["total"] = data["total"]; newObj["list_name"] = data["list_name"]; newObj["name"] = content["name"]; newObj["mobileNo"] = content["mobileNo"]; console.log(newObj)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM