简体   繁体   中英

How to manipulate json objects and add key using javascript?

This is the response i'm getting

result = [{
    "storeId": "4543",
    "type": "full",
    "overSerializedItems": [3548240, 91511753, 345555],
  },
  {
    "storeId": "5462",
    "type": "half",
    "overSerializedItems": [2548240, 9566666],
  }
]

I want to manipulate this json and add key to overSerializedItems.I want to manipulate the response data and need to convert this in below format

result = [{
    "storeId": "4543",
    "type": "full",
    "overSerializedItems": [
      {storeId: '3548240'},
      {storeId: '91511753'},
      {storeId: '345555'}
    ],
  },
  {
    "storeId": "5462",
    "type": "half",
    "overSerializedItems": [
      {storeId: '2548240'},
      {storeId: '9566666'}
    ],
  }
]

You can't have a multiple storeId key in an objet. But you can have multiple object with storeId.

overSerializedItems: [{storeId:...}, {storeId:...}]

You can transform like that:

var result = [
{
   "storeId": "4543",
   "type": "full",
   "overSerializedItems": [3548240,91511753,345555],
},
{
   "storeId": "5462",
   "type": "half",
   "overSerializedItems": [2548240,9566666],
}
];

 var trans = result.map(w => {
  return {
     storeId: w.storeId,
     type: w.type,
     overSerializedItems: w.overSerializedItems.map(x => { return {storeId: x.toString()} })
  }
})

You need to use two forEach() loop for that output:

 var result = [{ "storeId": "4543", "type": "full", "overSerializedItems": [3548240, 91511753, 345555], }, { "storeId": "5462", "type": "half", "overSerializedItems": [2548240, 9566666], } ]; result.forEach(function(obj){ obj.overSerializedItems.forEach(function(val, index){ obj.overSerializedItems[index] = {'store':val.toString()}; }); }); console.log(result);

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