javascript - 如何使用reduce将对象转换为对象数组?
问题描述
我想将对象转换为适合我需要的对象数组。我更喜欢使用最简单的解决方案和更少量的代码来编写。json 存储在“monitorings”变量中。
monitorings = [
{
"id": 1,
"survey_id": 1,
"region_id": 9101,
"month_id": 1,
"target": 22,
"progress": 22,
"survey": {
"name": "HPG",
"category": "SHP"
},
},
{
"id": 2,
"survey_id": 1,
"region_id": 9102,
"month_id": 1,
"target": 10,
"progress": 10,
"survey": {
"name": "SHPED",
"category": "SHPED"
},
},
}
]
我的大脑只能思考直到这段代码
Object.entries(
monitorings.reduce((monitorings, monitoring) => {
const { name } = monitoring.survey
monitorings[name] = monitorings[name]
? [...monitorings[name], monitoring]
: [monitoring]
return monitorings
}, {})
)
实际输出
[
"survey.name", [{grouped object}],
"survey.name", [{grouped object}],
]
预期产出
[
"survey.category", [
"survey.name", [{grouped object}],
"survey.name", [{grouped object}],
]
,
"survey.category", [
"survey.name", [{grouped object}],
"survey.name", [{grouped object}],
],
]
谢谢你的帮助
- 编辑 -
分组对象的格式与原始对象的格式相同,如下所示
[
{
"id": 2,
"survey_id": 1,
"region_id": 9102,
"month_id": 1,
"target": 10,
"progress": 10,
"survey": {
"name": "SHPED",
"category": "SHPED"
},
},
{same format as above},
{same format as above},
...
],
解决方案
我在这里找到了答案并对其进行了修改。
Object.entries(monitorings.reduce((map, obj) => {
!map[obj.survey["category"]]
? map[obj.survey["category"]] = {}
: [].concat(obj.survey["name"]).forEach(subEl => {
!map[obj.survey["category"]][subEl]
? map[obj.survey["category"]][subEl] = []
: map[obj.survey["category"]][subEl].push(obj);
})
return map;
}, {})
)
解释
//return convert object into array of object
Object.entries(
//return new form of object
monitorings.reduce((map, obj) => {
//if empty
!map[obj.survey["category"]]
//create new empty object of survey["category"]
? map[obj.survey["category"]] = {}
//else combine all of returned object of survey["name"] into empty array of object
: [].concat(obj.survey["name"])
//iterate over obj.survey["name"]
.forEach(subEl => {
//if that object is empty
!map[obj.survey["category"]][subEl]
//create empty array of survey["category"][subEl]
? map[obj.survey["category"]][subEl] = []
//else push every element of filtered original JSON into array of survey["category"][subEl]
: map[obj.survey["category"]][subEl].push(obj);
})
//return grouped object
return map;
}, {})
)
推荐阅读
- javascript - 在 JavaScript 中创建 N 维点网格
- node.js - NodeJS 客户端使用服务器流回响应
- javascript - Nuxt,过渡不适用于子路由(使用 NuxtChild 显示)
- forms - 谷歌脚本TextItem标题中的文本样式
- reactjs - MouseEnter/MouseOver 不适用于 react-testing-library。如何使用 react-testing-library 测试悬停事件
- xcode - XCODE:架构 x86_64 的未定义符号:
- android - 如何在firebase实时数据库中动态添加新节点
- stata - Stata 多项式回归 - 估计后 Wald 检验
- electron - Electronjs如何检测监视器/屏幕是否关闭
- reactjs - 未指定时如何在 React 组件中显式创建可选属性?