I have an array of objects each with a groupName key/value and then an item key with an array of objects as it's value.
I'm trying to use .reduce() with a forEach to iterate over the main array and merge all of the item values into a new Object with a single groupName and an items array containing all the original item values.
Every time I run the function I only get back the first value and I'm trying to figure out what I'm doing wrong.
Current Function:
const testMerge = moviesArray.reduce((acc, curr) => {
const { items } = curr;
items.forEach((el) => (acc[el] = el));
return acc;
}, {});
console.log('Test merge: ', testMergeObjects);
// returns [object Object]: groupName: The Town, year: 2010
moviesArray:
[
{
"groupName": "comedy",
"items": [
{
"name": "I Love You, Man",
"year": "2009"
}
]
},
{
"groupName": "sci fi",
"items": [
{
"name": "The Matrix",
"year": "1999"
},
{
"name": "Looper",
"year": "2012"
}
]
},
{
"groupName": "crime thriller",
"items": [
{
"name": "The Town",
"year": "2010"
}
]
}
]
Desired Result:
[
"groupName": "movies",
"items": [
{
"name": "I Love You, Man",
"year": "2009"
},
{
"name": "The Matrix",
"year": "1999"
},
{
"name": "Looper",
"year": "2012"
},
{
"name": "The Town",
"year": "2010"
}
]
]