将数组属性合并为新属性为“JSON字符串”

时间:2018-03-22 15:43:28

标签: javascript arrays json sorting

我正在尝试将数组的属性合并为类似JSON的字符串作为新属性。

给出类似的东西:

[{
   {
     "orderNo":"1",
     "description":"Item 1",
     "note": "Note 1"
   },
   {
     "orderNo":"2",
     "description":"Item 2",
     "note": "Note 2"
   },
   {
     "orderNo":"2",
     "description":"Item 3",
     "note": "Note 3"
   }
}]

将其转换为:

[{
   '0':[
      {
         'orderNo':'1',
         'items': '[{"description":"Item 1", "note": "Note 1"}]'
      }
   ],
   '1':[
      {
         'orderNo':'2',
         'items': '[{"description":"Item 2", "note": "Note 2"}, {"description":"Item 3", "note": "Note 3"}]'
      }
   ]
}]

使用以下函数(由@Barmar提供)我可以将一个属性累积到一个items数组中(在本例中为itemId)。

var newData = [];
for (var i = 0; i < data.length; i++) {
  var orderNo = data[i].orderNo;
  if (!newData[orderNo]) { // Add new object to result
    newData[orderNo] = {
      orderNo: orderNo,
      items: []
    };
  }
  newData[orderNo].items.push('{"itemId":' + data[i].itemId + ',"description:"' + data[i].description); // how than this be converted into a string?
}

如何将多个属性串在一起并保持关联,以便以后可以使用JSON.parse解析它们?

1 个答案:

答案 0 :(得分:1)

其中一种可能的方法如下。我使用 Array.prototype.forEach

&#13;
&#13;
x1=[{0:[{time:"2018-02-20",description:"Item 1",note:"Note 1"}],1:[{time:"2018-02-21",description:"Item 2",note:"Note 2"},{time:"2018-02-21",description:"Item 3",note:"Note 3"}]}];
var y1={};

x1.forEach(function(x){  // iterate through array of object
  var index=0;
  for(var a in x){       // iterate through all keys of object
    var y={};
    x[a].forEach(function(e){ //iterate through inner array
      y["time"]=e.time;       //crate new object of desire value
      if(!y["items"]){
        y["items"]=[];
      }
      y["items"].push({'description':e["description"],'note':e["note"]});     //push object into items property of object
    });
    y1[Object.keys(x[a])[index++]]=y; // create final object property and value
  }
});

console.log(y1);
&#13;
&#13;
&#13;