Skip to content
Advertisement

Javascript Mapping Array of Objects within an Array

I know there have been some similar questions before but I’m really stuck on trying to map the below array of information (I’ve tried to implement several example). I have an Array with two information fields and a third field that contains Arrays of objects. I want to extract the name of each of the objects into the original name so that my output looks like the below:

Desired Output:

[gameId, gameName, gameGenresArray]

Below is a sample of what the data looks like:

  Data = [ 270722, 'The Wild at Heart', [ [Object], [Object], [Object] ] ],
  [ 558984, 'Knockout City', [ [Object] ] ],
  [ 558982, 'Miitopia', [ [Object], [Object] ] ],
  [ 45775, 'Biomutant', [ [Object], [Object] ] ]

The [Object] has a property called gameGenre that I want to store in the original array as an array instead of as an Array of Objects.

My most recent attempt was:

var result = data.map(({ id, name, [{gameGenres}] }) => ([id, name, gameGenres]))

I appreciate any help anyone can add!

Thanks!!

Advertisement

Answer

I think this is what you want:

const Data = [
  [
    270722,
    'The Wild at Heart', [{
      name: 'action'
    }, {
      name: 'horror'
    }, {
      name: 'adventure'
    }],
  ],
  [558984, 'Knockout City', [{
    name: 'action'
  }]],
  [558982, 'Miitopia', [{
    name: 'action'
  }, {
    name: 'rpg'
  }]],
  [45775, 'Biomutant', [{
    name: 'casual'
  }, {
    name: 'platform'
  }]],
];

const result = Data.map(item => {
  return {
    gameId: item[0],
    gameName: item[1],
    gameGenresArray: item[2].map(genre => genre.name),
  };
});

console.log(result);
Advertisement