首页 > 解决方案 > 如何将数组对象分组为子对象并计算它们

问题描述

我从一个看起来像这样的 api 收到一个数组

input = [
  { choices:[
      {"food":"breakfast","preference":"tea"},
      {"food":"lunch","preference":"burger"},
      {"food":"supper","preference":"rice"}
    ]
  },
  { choices:[
      {"food":"breakfast","preference":"coffee"},
      {"food":"lunch","preference":"burger"},
      {"food":"supper","preference":"yam"}
    ]
  },
  { choices:[
      {"food":"breakfast","preference":"tea"},
      {"food":"lunch","preference":"bread"},
      {"food":"supper","preference":"yam"}
    ]
  },
  { choices:[
      {"food":"breakfast","preference":"coffee"},
      {"food":"lunch","preference":"bread"},
      {"food":"supper","preference":"rice"}
    ]
  }
]

我尝试了 Group by 基于属性的对象数组以及 javascript 中的计数

我需要对个人偏好进行分组并计算它们

groupedChoices = [
  [
    { "preference": "tea", "count": 3 },
    { "preference": "coffee", "count": 2 }
  ],
  [
    { "preference": "burger", "count": 3 },
    { "preference": "bread", "count": 2 }
  ],
  [
    { "preference": "rice", "count": 3 },
    { "preference": "yam", "count": 2 }
  ]
]

标签: javascriptarrays

解决方案


const input = [
  { choices:[
      {"food":"breakfast","preference":"tea"},
      {"food":"lunch","preference":"burger"},
      {"food":"supper","preference":"rice"}
    ]
  },
  { choices:[
      {"food":"breakfast","preference":"coffee"},
      {"food":"lunch","preference":"burger"},
      {"food":"supper","preference":"yam"}
    ]
  }, 
  {choices: [
      {"food":"breakfast","preference":"tea"},
      {"food":"lunch","preference":"bread"},
      {"food":"supper","preference":"yam"}
    ]
  },
  { choices:[
      {"food":"breakfast","preference":"coffee"},
      {"food":"lunch","preference":"bread"},
      {"food":"supper","preference":"rice"}
    ]
  }
];

const result = input.reduce((acc, { choices }) => {
  choices.forEach(({ food, preference }) => {
    if (!acc[food]) acc[food] = {}
    if (!acc[food][preference]) acc[food][preference] = 1
    else ++acc[food][preference]
  })
  return acc
}, {})

console.log(result)


推荐阅读