【发布时间】:2020-11-26 23:04:09
【问题描述】:
如果我有一个看起来像这样的示例数据,我需要从结果数组中获取 finalResult 数组:
let result = [{
type: ['Science'],
link: "www.educatorsector.com"
},
{
type: ['Sports', 'News'],
link: "www.skysports-news.com"
},
{
type: ['Sports', 'Science'],
link: "www.cnn-news.com"
}];
finalResult = [
{ type : "Science", numberOfLinks : 2 },
{ type : "Sports", numberOfLinks : 2 },
{ type : "News", numberOfLinks : 1 }]
orThisFinalResult = [
{ type : "Science", links : ["www.educatorsector.com", "www.cnn-news.com"],
{ type : "Sports", links : ["www.skysports-news.com", "www.cnn-news.com"],
{ type : "News", links : ["www.skysports-news.com"]
}
【问题讨论】:
-
您可以使用
Array#reduce在遍历数组时累积对象中的计数。然后通过Object#keys或类似方法将该对象转换为您想要的数组
标签: javascript arrays object es6-map