简体   繁体   中英

Remove duplicates from an array of objects in JavaScript But merge one field before removing the duplicates

I have the following variable:

var allProducts = [
    {"code": 1,"name": "productA", "category": ["fruits"],...},
    {"code": 1,"name": "productA", "category": ["vegetables"],...},
    {"code": 2,"name": "productB", "category": ["meat"],...},
    ...
]

So the only difference between the two repeated array of objects is the category ; where in this example code: 1 is once mentioned with category: ["fruits"] and another time with category: ["vegetables"] . Now I want to remove the duplicate but before doing so; I would like to save all the categories of productA into one category: ["fruits", "vegetables"] so the final variable would look like this:

var allProductsCleaned = [ 
    {"code": 1,"name": "productA", "category": ["fruits", "vegetables"],...},
    {"code": 2,"name": "productB", "category": ["meat"]...},
    ...
]

Here's an example:

  • Create an object with reduce:
    • save each object into the aggregated Object to test if "code" already added
    • if already present then merge the arrays
  • transform the object back to an array with Object.values()

 const allProducts = [ {"code": 1,"name": "productA", "category": ["fruits"]}, {"code": 1,"name": "productA", "category": ["vegetables"]}, {"code": 2,"name": "productB", "category": ["meat"]}, {"code": 2,"name": "productB", "category": ["fish"]}, {"code": 2,"name": "productB", "category": ["fish"]} ] const output = Object.values(allProducts.reduce((aggObj, item) => { if (aggObj[item.code]){ //item already exists so merge the category arrays: const newArr = [...new Set([...aggObj[item.code].category, ...item.category])] aggObj[item.code].category = newArr; }else{ //doesn't already exist: aggObj[item.code] = item; } return aggObj }, {})); console.log(output);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM