I have an array of objects that looks like:
const arr = [
{
"name": "Day",
"value": "Monday"
},
{
"name": "Month",
"value": "November"
},
{
"name": "Day",
"value": "Monday"
},
{
"name": "Month",
"value": "December"
},
{
"name": "Day",
"value": "Friday"
},
{
"name": "Month",
"value": "November"
},
{
"name": "Day",
"value": "Friday"
},
{
"name": "Month",
"value": "December"
}
]
but I'm needing to modify my array of objects to:
const final = [
{
"name": "Day",
"values": [
"Monday",
"Friday"
]
},
{
"name": "Month",
"values": [
"November",
"December"
]
}
]
I can filter out the duplicates with:
const filtered = arr.filter(
(v, i, a) =>
a.findIndex(v2 => v?.name === v2?.name && v?.value === v2?.value) === i
);
but I'm stuck on the approach on an efficient way to do this without Lodash or underscore and I've tried using Object.assign() but my implementation isn't working:
const test = filtered.map(({ name, value }) =>
Object.assign({ name, value: [] }, (name, value))
);
console.log(test)
Thought I had seen this asked before and tested answers from:
- How to merge an array with an object where values are arrays
- How to merge two array of objects by key AND keep unique keys in a single array of objects?
- From array of Object , get array of only matched key value
- From an array of objects, extract value of a property as array
- Merge multiple objects inside the same array into one object [duplicate]
In an array of objects and can I combine the objects with the same name but have the value in an array of strings?
reducerather thanmap, where you build up a new array as you iterate over each element. Although given what your final data looks like, I'm not sure an array is the right choice. Having a final object withdaysandmonthskeys that each point to an array of strings would be far easier to use in downstream code.reducewill get you there, andSetwill help remove the need to filter anything.