javascript - 使用不可变 javascript/node 的“真实世界”JSON 转换
问题描述
背景
我将使用数组的非平凡 JSON 响应转换为
- 嵌套对象
- 消除一些原始属性
- 插入一个新的汇总属性,它是来自原始对象的唯一值列表
我使用临时变量、foreach 循环和一些条件逻辑来做到这一点。我的第一个工作代码,示例输入/输出 JSON 如下。
问题/关注
虽然这可行,但我担心代码的“气味”和可维护性。有没有一种更易于维护的方法(也许使用 Array....、map、filter、reduce)?我不是在寻找一个可行的解决方案,而是寻找“一个衬里”。
代码
const raw = require('./tests/data/raw.json');
function parseLoc(loc) {
const types = new Set();
// constant properties with loc_id the name of the object
let o = { [loc.loc_id]: { last_update: loc.last_update, type_id: loc.type_id } };
types.add(loc.type_id);
// optional property
if (loc.contents) {
o = { [loc.loc_id]: { ...o[loc.loc_id], contents: loc.contents } };
loc.contents.forEach((item) => {
types.add(item.type_id); // can have nested types
});
}
// optional property
if (loc.plan_id) {
o = { [loc.loc_id]: { ...o[loc.loc_id], plan_id: loc.plan_id } };
}
// summary properties
o = {
[loc.loc_id]: {
...o[loc.loc_id],
Types: [...types],
},
};
return o;
}
const driver = () => {
const { locs } = raw[Object.keys(raw)[0]];
let out = {};
locs.forEach((loc) => {
const t = parseLoc(loc);
out = { ...out, [Object.keys(t)[0]]: t[Object.keys(t)[0]] };
});
console.log('out', out);
};
driver();
输入
{
"Input": {
"locs": [
{
"contents": [{ "amount": 1, "type_id": 2393 }],
"last_update": "2013-09-22T21:53:51Z",
"obsolete1": 1.52384062551,
"obsolete2": 1.56361060962,
"loc_id": 1011160470678,
"type_id": 2524
},
{
"last_update": "2019-07-29T10:56:27Z",
"obsolete1": 1.60921860432,
"obsolete2": 1.60545414964,
"loc_id": 1028580652821,
"plan_id": 97,
"type_id": 2474
},
{
"contents": [
{ "amount": 560, "type_id": 2393 },
{ "amount": 560, "type_id": 9838 },
{ "amount": 560, "type_id": 2317 },
],
"last_update": "2019-02-28T22:09:51Z",
"obsolete1": 1.55924075537,
"obsolete2": 1.58171860958,
"loc_id": 1029669382563,
"type_id": 2544
}
]
}
}
输出
{
"Output": {
"types": [2393, 9838, 2524, 2474, 2312],
"locs": {
"1011160470678": {
"last_update": "2013-09-22T21:53:51Z",
"type_id": 2524
},
"1028580652821": {
"contents": [{ "amount": 560, "type_id": 9838 }],
"last_update": "2019-07-29T10:56:27Z",
"plan_id": 97,
"type_id": 2474
},
"1029669382563": {
"contents": [
{ "amount": 560, "type_id": 2393 },
{ "amount": 560, "type_id": 9838 },
{ "amount": 560, "type_id": 2317 }
],
"last_update": "2019-02-28T22:09:51Z",
"type_id": 2544
}
}
}
}
解决方案
推荐阅读
- php - echo php 正在转换为 ascii
- xsd - 创建一个支持 web.config 转换或多租户/配置 xml 文件之类的 XSD
- reactjs - 如何在 React 重新渲染中重用 DOM 节点?
- java - aws cognito 中的分页获取用户
- react-native - 在 React Native 中使用类和渲染 api 调用
- python - 如何在Pygame中画一个小角度低速闪烁的运动圆圈?
- amazon-web-services - 使用 Amazon Cognito 进行手动身份验证
- javascript - npm 错误!在“...w2BfLygJAO9ZBvYIqZTld”附近解析时 JSON 输入意外结束
- ms-access - 根据文本框的值在选择查询中定义表
- javascript - Javascript:如何在对象中使用来自其他 getter 的 getter