javascript - 如何将数组对象分组为子对象并计算它们
问题描述
我从一个看起来像这样的 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 }
]
]
解决方案
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)
推荐阅读
- android - 丢失时如何创建新活动?
- regex - redash sql中可能出现的正则表达式回溯问题
- javascript - Skype Web 控制画布不可见
- html - 多个自定义复选框 (HTML) - 如何让它们彼此分开响应
- postgresql - 使 ST_Distance 查询在高负载下可扩展?
- sql-server - 如何使用夏令时 SSAS 表格强制唯一的 DateTime 值
- vba - MS Access 使用产品搜索创建销售系统
- angularjs - 多个量角器实例
- c# - 如何在 C# 中读取 json 时以编程方式转义特殊字符?
- python - pyparsing 在 emtpy delimitedList 上引发异常