删除对象数组重复项,并在数组中存储不重复的值



我需要合并一个包含注释的交付数组,我如何删除重复的对象,但仍保留注释字符串并将其存储在非重复对象的数组中

键开始发货号:

"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
}
]

"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
}
]

您可以使用Array.prototype.forEach()来遍历notes数组。如果一个音符出现两次,将它们的音符加在一起。

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)

最新更新