gpt4 book ai didi

javascript - 如何使用 JavaScript 或 Node 对 JSON 进行分组?

转载 作者:太空宇宙 更新时间:2023-11-04 00:51:00 25 4
gpt4 key购买 nike

我有一个音乐音频元数据的 JSON,其中包含以下结构的多个轨道:

var jsonObj = {
tracks: [
{ title: 'Another',
artist: 'Ataxia',
album: 'Automatic Writing',
year: '2004',
duration: 382
}]
};

我想将其转换为具有以下分组结构:

var jsonObj = {
artists: [
{ name: 'Ataxia',
albums: [
{ name: 'Automatic Writing',
year: '2004',
tracks: [
{ title: 'Another',
duration: '382'
}]
}]
}]
};

当然,我尝试使用纯 JavaScript forEach() 方法来完成此操作,但这是大量重复的、身临其境的代码,我正在寻找一些聪明的解决方案。它可以依赖一些外部 Node.js 包或 JavaScript 库。

最佳答案

组合艺术家和专辑的一个简单方法是使用字典。这是通过字典处理数据的一种方法,然后在按专辑和艺术家组织轨道后生成所需的数组。在控制台中查看结果。

var jsonObj = {
tracks: [{
title: 'Another',
artist: 'Ataxia',
album: 'Automatic Writing',
year: '2004',
duration: 382
}]
};

var byArtist = {};
jsonObj.tracks.forEach(function(e) {
if (byArtist[e.artist] === undefined) {
// New artist, add to the dictionary
byArtist[e.artist] = {
artist: e.artist,
albums: {}
};
}

if (byArtist[e.artist].albums[e.album] == undefined) {
// New album, add to the dictionary
byArtist[e.artist].albums[e.album] = {
name: e.album,
year: e.year,
tracks: []
};
}

// Add the track
byArtist[e.artist].albums[e.album].tracks.push({
title: e.title,
duration: e.duration
});
});

// Convert the dictionaries to the final array structure
var result = {
artists: []
};
for (var artistKey in byArtist) {
if (byArtist.hasOwnProperty(artistKey)) {
var artist = {
name: byArtist[artistKey].artist,
albums: []
};

// We need to convert the album dictionary as well
for (var albumKey in byArtist[artistKey].albums) {
if (byArtist[artistKey].albums.hasOwnProperty(albumKey)) {
artist.albums.push(byArtist[artistKey].albums[albumKey]);
}
}

result.artists.push(artist);
}
}

console.log(result);

关于javascript - 如何使用 JavaScript 或 Node 对 JSON 进行分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32445801/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com