Problem:
After searching, I found many solutions similar to the same idea, but I found it difficult to make the output in a specific format
data:
[
{
label: 'General-A-5',
paymentId: 1,
},
{
label: 'General-A-4',
paymentId: 1,
},
{
label: 'General-A-3',
paymentId: 2,
}
]
if paymentId id are the same then merge the label ( as string but split it with , )
output :
newArray [
{
label: 'General-A-5','General-A-4'
paymentId: 1,
},
{
label: 'General-A-3'
paymentId: 2,
}
]
thank you
Solution:
You can use the function ‘find()’ to check if you can find a match. If there is a match, push label into an array:
let list = [
{
label: 'General-A-5',
paymentId: 1,
},
{
label: 'General-A-4',
paymentId: 1,
},
{
label: 'General-A-3',
paymentId: 2,
}
];
let newlist = [];
// Simple approach
list.forEach(function(item) {
// Check if we can find the payment id in the new list
var match = newlist.find(function(i){
return i.paymentId === item.paymentId
})
// If we don't find it, just push it to the new list
if (!match) {
newlist.push(item)
} else {
// Check if match label is an array
// Otherwise convert it
if (!Array.isArray(match.label)){
match.label = [match.label]
}
// Now we can just push the label
match.label.push(item.label)
}
})
console.log(newlist)