0

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

1 Answer 1

1

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; }

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.