Background
I transformed a non-trivial JSON response that uses arrays into
- a nested object
- eliminating some of the original properties
- inserting a new summary property that is a unique list of values from the original object
I did this with temporary variables, foreach loops and some conditional logic. My first working code, sample input / output JSON are below.
Question / Concern
While this works, I'm concerned about the "smell" of the code and the maintainability. Is there a way to do this that would be more maintainable (perhaps with Array. ..., map, filter, reduce) ? I'm not looking for a working solution but more than "one liners".
CODE
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
{
"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
{
"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
}
}
}
}