我有一个类似于这样的对象数组:
[
{
"id": "1",
"location": "US"
},
{
"id": "7",
"location": "US"
},
{
"id": "1",
"location": "France"
},
{
"id": "1",
"location": "China"
}
]最后,我想得到一个如下所示的数组:
[
{
"id": "1",
"locations": ["US", "France", "China"]
},
{
"id": "7",
"locations": ["US"]
}
]是否有可靠的方法来使用下划线来完成这个任务?
我正在考虑遍历数组,对于每个id,循环遍历数组的其余部分,并将location值推送到第一个对象(按id)上的locations数组,最后删除不包含locations属性的所有重复对象(按id)。
这与现有的问题不同,因此只需简单地询问删除重复项。我的目标是移除副本,同时保留“幸存”对象数组中这些重复项的某些属性值。
发布于 2015-12-09 16:49:16
纯Javascript解决方案
var data = [{ "id": "9" }, { "id": "1", "location": "US" }, { "id": "7", "location": "US" }, { "id": "1", "location": "France" }, { "id": "1", "location": "China" }],
result = [];
data.forEach(function (a) {
a.location && !result.some(function (b) {
if (a.id === b.id) {
b.locations.push(a.location);
return true;
}
}) && result.push({ id: a.id, locations: [a.location] });
});
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
发布于 2015-12-09 16:50:19
您可以使用约简函数来转换数组。
var data = [
{ "id": "1", "location": "US" },
{ "id": "7", "location": "US" },
{ "id": "1", "location": "France" },
{ "id": "1", "location": "China" }
];
var result = data.reduce(function (prev, item) {
var newItem = prev.find(function(i) {
return i.id === item.id;
});
if (!newItem) {
prev.push({id: item.id, locations: [item.location]});
} else {
newItem.locations.push(item.location);
}
return prev;
}, []);https://stackoverflow.com/questions/34184135
复制相似问题