I have an array of objects with nested category objects (see below). I would like to remove the duplicate objects (based on "objectID") and create a new array with only the objects that have a higher amount of nested "hierarchicalCategories" key value pairs
const objectsArray = [
{
"objectID": 1234,
"hierarchicalCategories": {
"lvl0": "Women's",
"lvl1": "Women's > Shirts",
"lvl2": "Women's > Shirts > Tees"
}
},
{
"objectID": 5678,
"hierarchicalCategories": {
"lvl0": "Men's"
}
},
{
"objectID": 1234,
"hierarchicalCategories": {
"lvl0": "Women's"
}
},
{
"objectID": 5678,
"hierarchicalCategories": {
"lvl0": "Men's",
"lvl1": "Men's > Shoes"
}
}
]
So the expected result would look like this: The final array would filter duplicates and keep one instance of each object...the "objectID" : 1234 instance which had "hierarchicalCategories" up to "lvl2" and the "objectID" : 5678 instance which had "hierarchicalCategories" up to "lvl1"
const newArray = [
{
"objectID": 1234,
"hierarchicalCategories": {
"lvl0": "Women's",
"lvl1": "Women's > Shirts",
"lvl2": "Women's > Shirts > Tees"
}
},
{
"objectID": 5678,
"hierarchicalCategories": {
"lvl0": "Men's",
"lvl1": "Men's > Shoes"
}
}
]
I have this function which works for a new array based on filtering duplicate objectID's, but I am not sure how to create logic to keep the object with more "hierarchicalCategories" key value pairs.
const newArray = Array.from(new Set(objectsArray.map(a => a.objectID)))
.map(objectID => {
return objectsArray.find(a => a.objectID === objectID)
})