I am trying to merge the properties of an array into JSON-like string as a new property.
Given something like:
[{
{
"orderNo":"1",
"description":"Item 1",
"note": "Note 1"
},
{
"orderNo":"2",
"description":"Item 2",
"note": "Note 2"
},
{
"orderNo":"2",
"description":"Item 3",
"note": "Note 3"
}
}]
And converting it into:
[{
'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"}]'
}
]
}]
Using the following function (supplied by @Barmar) I can accumulate a single property into an items array (in this case, 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?
}
How can I string multiple properties together and maintain their association so that they can be later parsed with JSON.parse
?