I need to merge an array of deliveries that have notes, how would I remove the duplicate object but still keep the note string and store it in an array for the non duplicated object
Key begin the delivery number:
"data": [
{
"deliveryNumber": "0000001",
"deliveryDate": "2021-10-01T00:00:00.000Z",
"dateBeginProcess": null,
"dateFinishedProcess": null,
"status": "",
"notes": "Note 1"
},
{
"deliveryNumber": "0000001",
"deliveryDate": "2021-10-01T00:00:00.000Z",
"dateBeginProcess": null,
"dateFinishedProcess": null,
"status": "Ready",
"notes": "Note 2"
},
{
"deliveryNumber": "0000002",
"deliveryDate": "2021-10-01T14:21:00.000Z",
"dateBeginProcess": null,
"dateFinishedProcess": null,
"status": "Ready",
"notes": null
}
]
into
"data": [
{
"deliveryNumber": "0000001",
"deliveryDate": "2021-10-01T00:00:00.000Z",
"dateBeginProcess": null,
"dateFinishedProcess": null,
"status": "Ready",
"notes": ["Note 1", "Note 2"]
},
{
"deliveryNumber": "0000002",
"deliveryDate": "2021-10-01T14:21:00.000Z",
"dateBeginProcess": null,
"dateFinishedProcess": null,
"status": "Ready",
"notes": null
}
]
CodePudding user response:
You can use Array.prototype.forEach()
to loop over the notes array. If a note is encountered twice add their notes together.
const notes = [
{
"deliveryNumber": "0000001",
"deliveryDate": "2021-10-01T00:00:00.000Z",
"dateBeginProcess": null,
"dateFinishedProcess": null,
"status": "",
"notes": "Note 1"
},
{
"deliveryNumber": "0000001",
"deliveryDate": "2021-10-01T00:00:00.000Z",
"dateBeginProcess": null,
"dateFinishedProcess": null,
"status": "Ready",
"notes": "Note 2"
},
{
"deliveryNumber": "0000002",
"deliveryDate": "2021-10-01T14:21:00.000Z",
"dateBeginProcess": null,
"dateFinishedProcess": null,
"status": "Ready",
"notes": null
}
]
let filteredArray = []
notes.forEach(note => {
let noteFound = filteredArray.find(el => el.deliveryNumber === note.deliveryNumber)
if(noteFound){
// not first encounter
// add notes together
noteFound.notes.push(note.notes)
}else{
// first encounter
// make notes an array
note.notes = [note.notes||'']
filteredArray.push(note)
}
})
console.log(filteredArray)