使用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' }, ... ]
[ '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' } }, ... ]
最好的方法是什么?我对JS比较新,所以可能很简单.
只是用 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('' + JSON.stringify(grouped, 0, 4) + '
');