简体   繁体   中英

How to change JSON format?

I want to change the below JSON Data to Expected Format.

JSON DATA:

[
  {
    "A": {
      "X": "P"
    },
    "B": {
      "X": "Q"
    },
    "C": {
      "X": "R"
    }
  }
]

Expected Format:

[
  {  
    "A": "P",
    "B": "Q",
    "C": "R"
  }      
]

Thanks in advance. :)

Try this. You can get the keys of the each item and then map to the correspond structure of object.

 const json = [ { "A":{ "X":"P" }, "B":{ "X":"Q" }, "C":{ "X":"R" } } ]; const expectedJSON = json.map(item => { const obj = {}; Object.keys(item).forEach(key => obj[key] = item[key].X); return obj; }) console.log(expectedJSON);

In case X property has different names for each object you can use this method.

 const json = { "A": { "X": "P" }, "B": { "X": "Q" }, "C": { "X": "R" } }; for (let prop in json) { for (let item in json[prop]) { json[prop] = json[prop][item]; } } console.log(json);

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