如何使用Javascript将具有相同名称的对象分组?

Kie*_*n E 2 javascript json node.js electron

使用Node,我正在实现一个ID3标签解析器来获取MP3的标题,专辑和艺术家.

现在,我需要获取我收到的信息,并按照专辑名称对它们进行分组.

在我的具体用法中,我试图从中走出来

这个:

[
  { 
    title: 'Break You',
    artist: 'Lamb Of God',
    album: 'Ashes Of The Wake' 
  },
  {
    title: 'An Extra Nail For Your Coffin',
    artist: 'Lamb Of God',
    album: 'Ashes Of The Wake' 
  },
  {
    title: 'Envy And Doubt',
    artist: 'Sever The King',
    album: 'Traitor' 
  },
  {
    title: 'Self Destruct',
    artist: 'Sever The King',
    album: 'Traitor' 
  },
  ...
]
Run Code Online (Sandbox Code Playgroud)

对此:(伪代码)

[
  'Ashes Of The Wake'{
    {
      title: 'Break You',
      artist: 'Lamb Of God'
    },
    {
      title: 'An Extra Nail For Your Coffin',
      artist: 'Lamb Of God'
    }  
  }
  'Traitor'{
    {
      title: 'Envy and Doubt',
      artist: 'Sever The King'
    },
    {
      title: 'Self Destruct',
      artist: 'Sever The King'
    }
  },
  ...
]
Run Code Online (Sandbox Code Playgroud)

最好的方法是什么?我对JS比较新,所以可能很简单.

Nin*_*olz 6

只是用 Array.prototype.forEach()

forEach()方法每个数组元素执行一次提供的函数.

var data = [{ title: 'Break You', artist: 'Lamb Of God', album: 'Ashes Of The Wake' }, { title: 'An Extra Nail For Your Coffin', artist: 'Lamb Of God', album: 'Ashes Of The Wake' }, { title: 'Envy And Doubt', artist: 'Sever The King', album: 'Traitor' }, { title: 'Self Destruct', artist: 'Sever The King', album: 'Traitor' }],
    grouped = {};

data.forEach(function (a) {
    grouped[a.album] = grouped[a.album] || [];
    grouped[a.album].push({ title: a.title, artist: a.artist });
});
document.write('<pre>' + JSON.stringify(grouped, 0, 4) + '</pre>');
Run Code Online (Sandbox Code Playgroud)