Josh
Josh

Reputation: 1235

Trying to merge nested properties of objects inside array into single object containing all nested properties using reduce, only getting single value

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"
    }
  ]
]

Upvotes: 0

Views: 130

Answers (1)

Hassan Imam
Hassan Imam

Reputation: 22534

You can use array#map and array#concat to merge items in movie array.

const data = [ { "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" } ] } ],
      items = [].concat(...data.map(({items}) => items)),
      output = { groupName: "movies", items}
console.log(output);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 1

Related Questions