I have problem with array JSON. I think it nested group by the first is group by _id and second one is group by itemId I do not know how to solve it,Please help me
let data=[
{
"_id" : "013",
"items" : [
{
"itemId" : "4",
"stockIn" : 50,
"stockOut" : 0
},
{
"itemId" : "9",
"stockIn" : 100,
"stockOut" : 0
}
]
},
{
"_id" : "013",
"items" : [
{
"itemId" : "3",
"noFreeQtyCount" : 20,
"freeQtyCount" : 0
},
{
"itemId" : "9",
"noFreeQtyCount" : 30,
"freeQtyCount" : 0
}
]
}
]
This is my data that I want
[
{
"_id" : "013",
"items" : [
{
"itemId" : "3",
"noFreeQtyCount" : 20,
"freeQtyCount" : 0
},
{
"itemId" : "4",
"stockIn" : 50,
"stockOut" : 0
},
{
"itemId" : "9",
"stockIn" : 100,
"stockOut" : 0
"noFreeQtyCount" : 30,
"freeQtyCount" : 0
}
]
},
]
This my script please help
const groupBy = data.reduce((acc, cur) => {
acc[cur._id] ? acc[cur._id].items = [...acc[cur._id].items, ...cur.items] : acc[cur._id] = cur;
return acc;
}, {});
const output = groupBy;
print(output);
>Solution :
You can use Object.key(), Array.prototype.map() and Object.assign() accomplish the grouping you need.
Refer the code below:
function groupByItemId(data) {
const mergedData = {};
data.forEach(entry => {
const _id = entry["_id"];
const items = entry["items"];
if (!mergedData[_id]) {
mergedData[_id] = {};
}
items.forEach(item => {
const itemId = item["itemId"];
if (!mergedData[_id][itemId]) {
mergedData[_id][itemId] = {};
}
Object.assign(mergedData[_id][itemId], item);
});
});
const result = Object.keys(mergedData).map(_id => {
return {"_id": _id, "items": Object.values(mergedData[_id])};
});
return result;
}
const inputData = [
{
"_id": "013",
"items": [
{"itemId": "4", "stockIn": 50, "stockOut": 0},
{"itemId": "9", "stockIn": 100, "stockOut": 0},
],
},
{
"_id": "013",
"items": [
{"itemId": "3", "noFreeQtyCount": 20, "freeQtyCount": 0},
{"itemId": "9", "noFreeQtyCount": 30, "freeQtyCount": 0},
],
},
];
const result = groupByItemId(inputData);
console.log(result);