当我在Javascript中处理对象数组时,我遇到了问题。
问题:输入
[ { "artistName": "NgaNguyen Duy", "workId": "554a9e4fa36f794b31000024" }, { "artistName": "NgaNguyen Duy", "workId": "554d3ffbcc477a7110000003" }, { "artistName": "Kristin", "workId": "557a4kfbcc5e2a7110000223" } ]
输出应该是:
[ { "artistName": "NgaNguyen Duy", "workId" : ["554a9e4fa36f794b31000024", "554d3ffbcc477a7110000003"] }, { "artistName": "Kristin", "workId": ["557a4kfbcc5e2a7110000223"] } ]
提前感谢。
答案 0 :(得分:1)
You can do aggregate :
var t = [
{
"artistName": "NgaNguyen Duy",
"workId": "554a9e4fa36f794b31000024"
},
{
"artistName": "NgaNguyen Duy",
"workId": "554d3ffbcc477a7110000003"
},
{
"artistName": "Kristin",
"workId": "557a4kfbcc5e2a7110000223"
}
];
var u = {};
var res = [];
t.forEach(function(item){
if(!u[item.artistName]){
u[item.artistName] = [];
}
u[item.artistName].push(item.workId);
});
for(var key in u){
res.push({'artistName':key,'workId':u[key]});
}
console.log(res);
https://jsfiddle.net/Lgbcxorj/
答案 1 :(得分:1)
所以你想合并“workId”的同名条目?:
var artists_in = [
{
"artistName": "NgaNguyen Duy",
"workId": "554a9e4fa36f794b31000024"
},
{
"artistName": "NgaNguyen Duy",
"workId": "554d3ffbcc477a7110000003"
},
{
"artistName": "Kristin",
"workId": "557a4kfbcc5e2a7110000223"
}
]
var artists_out = {}
for (i = 0; i < artists_in.length; i++)
{
artistKey = artists_in[i]["artistName"];
if(artists_out[artistKey] == null)
{
artists_out[artistKey] = { "artistName": artistKey, "workId": [artists_in[i]["workId"]] };
}
else
{
artists_out[artistKey]["workId"].push(artists_in[i]["workId"]);
}
}
console.log(artists_out);