删除对象数组重复项并将非重复值存储在数组中

Remove object array duplicates and store non duplicate values in array

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

键开始交货编号:

"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)