我有一个数组:
const arr = [
{ name: "aa", type: "total", count: 28394 },
{ name: "aa", type: "featured", count: 4 },
{ name: "aa", type: "noAnswers", count: 5816 },
{ name: "ba", type: "total", count: 148902 },
{ name: "ba", type: "featured", count: 13 },
{ name: "ba", type: "noAnswers", count: 32527 },
{ name: "cc", type: "total", count: 120531 },
{ name: "cc", type: "featured", count: 6 },
{ name: "cc", type: "noAnswers", count: 24170 }
];
const arrResult = [
{ name: "aa", total: 28394, featured: 4, noAnswers: 5816 },
{ name: "ba", total: 148902, featured: 13, noAnswers: 32527 },
{ name: "cc", total: 120531, featured: 6, noAnswers: 24170 }
];
我想出了这段代码:
let output = [];
const unique = [...new Set(arr.map(item => item.name))];
for(const key of unique) {
let result = arr.filter(x => {
return x.name === key;
});
output.push({
name: key,
// need to get the rest of the properties here
// total
// featured
// noAnswers
});
}
我唯一想不通的是如何获取属性名称。 有什么想法吗?
最佳答案
你可以尝试这样的事情:
想法:
- 创建一个 hashMap,以便您可以通过
name
对对象进行分组。 - 然后,向该组添加必要的属性。
- 最后,遍历键并创建添加回 name 属性的最终对象。
const arr = [ { name: "aa", type: "total", count: 28394 }, { name: "aa", type: "featured", count: 4 }, { name: "aa", type: "noAnswers", count: 5816 }, { name: "ba", type: "total", count: 148902 }, { name: "ba", type: "featured", count: 13 }, { name: "ba", type: "noAnswers", count: 32527 }, { name: "cc", type: "total", count: 120531 }, { name: "cc", type: "featured", count: 6 }, { name: "cc", type: "noAnswers", count: 24170 } ];
const hashMap = arr.reduce((acc, item) => {
acc[item.name] = acc[item.name] || {};
acc[item.name][item.type] = item.count;
return acc;
}, {});
const result = Object.keys(hashMap).map((name) => Object.assign({}, {name}, hashMap[name] ));
console.log(result)
工作:
我正在做的是为每个新的 name
创建一个新对象。所以,这个: acc[item.name] = acc[item.name] || {};
检查条目是否不可用。
- 如果不可用,返回一个新对象。
- 如果可用,返回相同对象的引用。
因此对于任何给定的名称,您只会指代相同的对象。
现在:acc[item.name][item.type] = item.count
设置属性。由于我们指的是同一个对象,您在一个地方设置属性。所以如果你有重复的条目,比如
[
{ name: "aa", type: "total", count: 28394 },
{ name: "aa", type: "total", count: 123},
]
输出将有 total: 123
而不是。
所以,最后,您的结构如下:
{
aa: {
total: <something>,
feature: <something>,
...
}
}
现在您所要做的就是合并这个对象中的名称并返回值。您还可以创建默认具有 name
属性的对象(由 adiga 完成)。这是我在回答时没有想到的。所以记分而不是回答。
关于javascript - 如何将一个数组转换为另一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54230171/