I'm attempting to combine the attributes of an array into a JSON-like string as a new attribute.
For example:
[{
{
"orderNo":"1",
"description":"Item 1",
"note": "Note 1"
},
{
"orderNo":"2",
"description":"Item 2",
"note": "Note 2"
},
{
"orderNo":"3",
"description":"Item 3",
"note": "Note 3"
}
}]
And transforming 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"}]'
}
]
}]
With the provided function (from @Barmar), I can accumulate a single attribute 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 concatenate multiple attributes together while preserving their relationship so they can later be parsed with JSON.parse
?