我正在尝试找到一种优雅而有效的方法,将对象数组转换为由键索引的对象(在本例中为"groupByThisKey"(。我相信它被称为哈希图。
我能够想出一个原始版本
下面用一些数据解释:
const arr = [
{
id: 1,
name: "one",
groupByThisKey: 'groupA'
},
{
id: 2,
name: "two",
groupByThisKey: 'groupB'
},
{
id: 3,
name: "three",
groupByThisKey: 'groupB'
},
{
id: 4,
name: "four",
groupByThisKey: 'groupA'
}
];
const groupedByKey = {};
arr.map(obj => {
if (groupedByKey[obj.groupByThisKey])
groupedByKey[obj.groupByThisKey].push(obj)
else
groupedByKey[obj.groupByThisKey] = [obj]
});
console.log(groupedByKey)
它确实给出了所需的输出:
{
groupA: [
{
id: 1,
name: "one",
groupByThisKey: 'groupA'
},
{
id: 4,
name: "four",
groupByThisKey: 'groupA'
}
],
groupB: [
{
id: 2,
name: "two",
groupByThisKey: 'groupB'
},
{
id: 3,
name: "three",
groupByThisKey: 'groupB'
}
]
}
但以一种相当原始的方式。我宁愿使用更短、更现代的方式来做到这一点,如果可能的话,可能会使用 object.assign 或 reduce,但不能绕开它,因为我需要每个键的值数组。
我能够找到许多示例,这些示例似乎都适用于每个键只有一个值的用例,但就我而言,我需要按该键分组的对象数组,因此我找到的示例只会采用最新的。下面是一个示例:
const hash = Object.assign({}, ...array.map(s => ({[s.key]: s.value})));
你实现的东西是非常正确的,让我通过使用化简器来消除副作用:
const arr = [
{
id: 1,
name: "one",
groupByThisKey: 'groupA'
},
{
id: 2,
name: "two",
groupByThisKey: 'groupB'
},
{
id: 3,
name: "three",
groupByThisKey: 'groupB'
},
{
id: 4,
name: "four",
groupByThisKey: 'groupA'
}
];
console.log(arr.reduce((groupedByKey,obj) => {
if (groupedByKey[obj.groupByThisKey])
groupedByKey[obj.groupByThisKey].push(obj)
else
groupedByKey[obj.groupByThisKey] = [obj]
return groupedByKey;
}, {}));
在这里,你走最fp式的写作方式。不是真正的performat,下面的下一个版本(在此之后(将具有更好的性能,因为它不是在非常迭代中创建对象或数组的新版本。
const arr = [
{
id: 1,
name: "one",
groupByThisKey: 'groupA'
},
{
id: 2,
name: "two",
groupByThisKey: 'groupB'
},
{
id: 3,
name: "three",
groupByThisKey: 'groupB'
},
{
id: 4,
name: "four",
groupByThisKey: 'groupA'
}
];
console.log(arr.reduce(
(groups, x) =>
({
...groups,
[x.groupByThisKey]: [
...(groups[x.groupByThisKey] || []),
x
]
})
, {}
))
具有与上述相同逻辑的更简单版本:
const arr = [
{
id: 1,
name: "one",
groupByThisKey: 'groupA'
},
{
id: 2,
name: "two",
groupByThisKey: 'groupB'
},
{
id: 3,
name: "three",
groupByThisKey: 'groupB'
},
{
id: 4,
name: "four",
groupByThisKey: 'groupA'
}
];
console.log(arr.reduce(
(groups, x) => {
let key = x.groupByThisKey;
if (groups[key] === undefined)
groups[key] = [];
groups[key].push(x);
return groups;
}, {}
))
现代方式将使用Map
,而不是对象:
const groupedByKey = new Map();
for (const obj of arr) {
if (!groupedByKey.has(obj.groupByThisKey))
groupedByKey.set(obj.groupByThisKey, []);
groupedByKey.get(obj.groupByThisKey).push(obj);
}