首页 > 解决方案 > Javascript - 通过键数组对对象数组进行分组

问题描述

我有这个问题,我想将每个包含类型数组的对象数组分组到数组对象中。

开始:

const start = [
    { name: "Banana", type: ['fruit'] },
    { name: 'Apple', type: ['fruit', 'food'] }, 
    { name: 'Carrot', type: ['vegetable', 'food'] }
 ]

期望的结果

  const desiredResult = {
    'fruit':[
      { name: "Banana", type: ['fruit'] },
      { name: 'Apple', type: ['fruit', 'food'] }
    ],
    'food': [
        { name: 'Apple', type: ['fruit', 'food'] },
        { name: 'Carrot', type: ['vegetable', 'food'] }
     ],
     'vegetable':[
         { name: 'Carrot', type: ['vegetable', 'food'] }
     ]
  };

我被困在哪里,不知道现在如何映射该类型数组:D 目前只有 a.type[0],这很糟糕。

const groupedData = start.reduce(function (r, a) {
   r[a.type[0]] = r[a.type[0]] || [];
   r[a.type[0]].push(a);
   return r;
}, {});

标签: javascriptarrays

解决方案


您需要遍历a.type.

const groupedData = start.reduce(function(r, a) {
  a.type.forEach(type => {
    r[type] = r[type] || [];
    r[type].push(a);
  });
  return r;
}, {});


推荐阅读