Javascript – Group by data from object arrays

I have the object arrays like below:

const obj = {
  top: [
    { id: 1, name: "Spider-man", rating: 1 },
    { id: 2, name: "Iron man", rating: 3 },
    { id: 3, name: "Hulk", rating: 5 }
  ],
  middle: [
    { id: 1, name: "Spider-man", rating: 4.5 },
    { id: 2, name: "Iron man", rating: 3.5 },
    { id: 3, name: "Hulk", rating: 1.5 }
  ],
  bottom: [
    { id: 1, name: "Spider-man", rating: 5 },
    { id: 2, name: "Iron man", rating: 2 },
    { id: 3, name: "Hulk", rating: 4 }
  ]
};

And what I want is to group by id, name and list out rating belonging its like below

const users = [
  {
    id: 1,
    name: "Spider-man",
    rating: {top: 1, middle: 4.5, bottom: 5}
  },
  {
    id: 2,
    name: "Iron man",
    rating: {top: 3, middle: 3.5, bottom: 2}
  },
  {
    id: 3,
    name: "Hulk",
    rating: {top: 5, middle: 1.5, bottom: 4}
  }
];

I’ve tried this approach but seems it can achieve in more ways such as .reduce, for...of with more elegant, right?

const obj = {
  top: [
    { id: 1, name: "Spider-man", rating: 1 },
    { id: 2, name: "Iron man", rating: 3 },
    { id: 3, name: "Hulk", rating: 5 }
  ],
  middle: [
    { id: 1, name: "Spider-man", rating: 4.5 },
    { id: 2, name: "Iron man", rating: 3.5 },
    { id: 3, name: "Hulk", rating: 1.5 }
  ],
  bottom: [
    { id: 1, name: "Spider-man", rating: 5 },
    { id: 2, name: "Iron man", rating: 2 },
    { id: 3, name: "Hulk", rating: 4 }
  ]
};

var result = obj.top.map(x => ({
  id: x.id,
  name: x.name,
  rating: {
    top: obj.top.find(t => t.id === x.id).rating,
    middle: obj.middle.find(t => t.id === x.id).rating,
    bottom: obj.bottom.find(t => t.id === x.id).rating,
  }
}));
                          
console.log(result);

Any other ways to achieve it? Thanks in advance.

53 thoughts on “Javascript – Group by data from object arrays”

  1. 477109 580679This really is a terrific internet site, could you be interested in performing an interview about just how you produced it? If so e-mail me! 507811

    Reply

Leave a Comment