如果我有一个如下所示的示例数据,我需要从结果数组中获取 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 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce创建一个对象来计算每个对象的所有链接type
;然后使用Object.entries https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries将这些值作为数组获取,最后使用Array.map https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map转换为对象数组:
let result = [{
type: ['Science', 'Business'],
link: "www.educatorsector.com"
},
{
type: ['Sports', 'News'],
link: "www.skysports-news.com"
},
{
type: ['Sports', 'Health', 'Science'],
link: "www.cnn-news.com"
},
{
type: ['Health'],
link: "www.healthsector.com"
}
];
let output = Object.entries(result
.reduce((c, o) => {
o.type
.forEach(t => c[t] = (c[t] || 0) + 1);
return c;
}, {}))
.map(([type, numberOfLinks]) => ({
type,
numberOfLinks
}));
console.log(output);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)