Reputation: 9
My array is something like this:
myArray = [
{SKU: "Hoo12", Name: "ACyrlic watch",OrderNo:"26423764233456"},
{SKU: "S0002", Name: "Princes Geometry",OrderNo:"124963805662313"},
{SKU: "Hoo12", Name: "ACyrlic watch",OrderNo:"122324234234"},
]
I want to convert
OutPut = [
{SKU: "Hoo12",Name: "ACyrlic watch", OrderNo: ["26423764233456", "122324234234"]}
{SKU: "S0002", Name: "Princes Geometry", OrderNo: ["124963805662313"]}
]
I want try many methods but I just don't know how to handle the grouping of similar group values.
Upvotes: 1
Views: 70
Reputation: 5308
Using reduce
method, you can achieve your expected output
const myArray = [ {SKU: "Hoo12", Name: "ACyrlic watch",OrderNo:"26423764233456"}, {SKU: "S0002", Name: "Princes Geometry",OrderNo:"124963805662313"}, {SKU: "Hoo12", Name: "ACyrlic watch",OrderNo:"122324234234"}];
const result = Object.values(myArray.reduce((a,{OrderNo, ...r})=>{
a[r.SKU] ??= {...r, OrderNo:[]};
a[r.SKU].OrderNo.push(OrderNo)
return a;
},{}));
console.log(result);
Upvotes: 1
Reputation: 1878
A simple forEach
should do, if you do not want to modify the initial myArray
(pure function)
// Initialization
myArray = [
{SKU: "Hoo12", Name: "ACyrlic watch",OrderNo:"26423764233456"},
{SKU: "S0002", Name: "Princes Geometry",OrderNo:"122324234234"},
{SKU: "Hoo12", Name: "ACyrlic watch",OrderNo:"122324234234"},
]
OutPut = []
// For each element of the array
myArray.forEach(elem => {
// find the one that match with SKU and Name
let found = OutPut.find(o => o.SKU == elem.SKU && o.Name == elem.Name)
// if it present add the OrderNo
if (found) {
found.OrderNo.push(elem.OrderNo)
}
// else add the object with OrderNo as an Array
else {
OutPut.push({ SKU: elem.SKU, Name: elem.Name, OrderNo: [ elem.OrderNo ] })
}
})
// Show output
let c = document.createElement('pre');
c.innerText = JSON.stringify(OutPut, null, 2)
document.body.appendChild(c)
Upvotes: 0
Reputation: 24181
Whenever you see data that's grouping Array.reduce is a good candidate.
eg.
const myArray = [
{SKU: "Hoo12", Name: "ACyrlic watch",OrderNo:"26423764233456"},
{SKU: "S0002", Name: "Princes Geometry",OrderNo:"124963805662313"},
{SKU: "Hoo12", Name: "ACyrlic watch",OrderNo:"122324234234"},
];
const OutPut = myArray.reduce((a,v) => {
let c = a.find(f => f.SKU === v.SKU);
//do we have this SKU..
if (!c) {
//No lets add
c = v;
c.OrderNo = [v.OrderNo];
a.push(c);
} else {
//Yes, lets add this OrderNo.
c.OrderNo.push(v.OrderNo);
}
return a;
}, []);
console.log(OutPut);
Upvotes: 1