有人知道从中转换的干净解决方案吗?
var foo1 = [
{
"value":"1",
"key":"abc"
},
{
"value":"2",
"key":"abc"
},
{
"value":"3",
"key":"def"
}
];
到
var foo2 = [
{
"value":["1","2"],
"key":"abc"
},
{
"value":"3",
"key":"def"
}
];
答案 0 :(得分:0)
您可以使用数组reduce
和findIndex
。 acc
是累加器数组。在累加器数组中,使用findIndex
查看是否存在具有相同键的对象。如果存在,则更新对象的值,否则在累加器数组中添加具有所需参数的新对象
var foo1 = [{
"value": "1",
"key": "abc"
},
{
"value": "2",
"key": "abc"
},
{
"value": "3",
"key": "def"
}
];
let groupedBy = foo1.reduce(function(acc, curr) {
let ifHasKey = acc.findIndex(function(item) {
return item.key === curr.key;
})
if (ifHasKey === -1) {
acc.push({
value: [curr.value],
key: curr.key
})
} else {
acc[ifHasKey].value.push(curr.value)
}
return acc;
}, []);
console.log(groupedBy)
答案 1 :(得分:0)
您可以使用Map
对项目进行分组,然后为结果集构建新对象。
var array = [{ value: "1", key: "abc" }, { value: "2", key: "abc" }, { value: "3", key: "def" }],
grouped = Array.from(
array.reduce((m, { key, value }) => m.set(key, [...(m.get(key) || []), value]), new Map),
([key, value]) => ({ key, value })
);
console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }