首页 > 解决方案 > 从大列表中提取数据

问题描述

我有一个如下列表:

var list = [
  {
    id:1,
    name: 'bss',
    type_a: 1, 
  },
  {
    id:2,
    name: 'bss',
    type_a: 1,
  },
  {
    id:3,
    name: 'bss',
    type_a: 2,
  },
  {
    id:4,
    name: 'bss',
    type_a: 2,
  },
  {
    id:6,
    name: 'bss',
    type_a: 2,
  },

  {
    id:8,
    name: 'bss',
    type_a: 5,
  },

  {
    id:9,
    name: 'bss',
    type_a: 8,
  },
  ...
]

你看到列表,列表中的项目有一个type_a参数:

我想提取type_a出来,并将相同的 type_a 聚合成这样:

{
  8: [  // the 8 is `type_a`
    {
        id:9,
        name: 'bss',
        type_a: 8,
      },
    ], 
  },
  5: [
    {
        id:8,
        name: 'bss',
        type_a: 5,
      },
  ] 
  ...
}

是否有更高效的功能来实现这一点?

我可以使用两个 for 循环来实现这一点,第一个是收集 type_a 类型,另一个用于列表,如果等于type_a项目。

标签: javascriptmath

解决方案


您可以Array.reduce()用于该输出:

var list = [
  {
    id:1,
    name: 'bss',
    type_a: 1, 
  },
  {
    id:2,
    name: 'bss',
    type_a: 1,
  },
  {
    id:3,
    name: 'bss',
    type_a: 2,
  },
  {
    id:4,
    name: 'bss',
    type_a: 2,
  },
  {
    id:6,
    name: 'bss',
    type_a: 2,
  },

  {
    id:8,
    name: 'bss',
    type_a: 5,
  },

  {
    id:9,
    name: 'bss',
    type_a: 8,
  }
];

var res = list.reduce((acc, item)=>{
  if(acc[item.type_a]){
    acc[item.type_a].push(item);
    return acc;
  }
  acc[item.type_a] = [];
  acc[item.type_a].push(item);
  return acc;
}, {});
console.log(res);


推荐阅读