-2

如果我有一个看起来像这样的示例数据,我需要从结果数组中获取 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"]
 }
4

2 回答 2

2

用于Array.flatMap()获取类型数组。将类型数组减少为计数映射。将 Map 转换为条目数组,然后将其映射到对象数组:

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);

于 2020-11-27T00:17:15.900 回答
2

您可以使用Array.reduce创建一个对象来计算每个链接的所有链接type;然后用于Object.entries将这些值作为数组获取,最后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);

于 2020-11-26T23:14:07.710 回答