问题
If I have a sample data that looks like this I need to get finalResult array from result array:
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"]
}
回答1:
You can use Array.reduce to create an object which counts all the links for each type
; then use Object.entries to get those values as an array, finally using Array.map to convert to an array of objects:
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);
回答2:
Use Array.flatMap()
to get an array of types. Reduce the array of types to a Map of counts. Convert the Map to an array of entries, and then map it to an array of objects:
const 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"}];
const counts = Array.from(
result
.flatMap(o => o.type) // flatten to array of types
.reduce((acc, type) => // create a Map of counts
acc.set(type, (acc.get(type) || 0) + 1),
new Map)
)
.map(([type, numberOfLinks]) => ({ type, numberOfLinks })); // convert the Map's entries to an array of objects
console.log(counts);
来源:https://stackoverflow.com/questions/65030227/create-a-new-result-from-an-existing-array