What I need to do is modify a TypeScript object by doing a key search (the key can be repeated, so I need to check that it belongs to the right branch) and modifying the corresponding object. In short if this is the object:
{
requirements: {
general_info: {
aircraft: {
payload: { '@_unit': 'kg' },
autopilot_ratio: '',
},
power: {
number_of_engines: '',
},
geometrical: {
payload: { '@_unit': 'kg' },
design_approach: { target: '' },
},
},
},
}
must be transformed into:
{
requirements: {
general_info: {
aircraft: {
payload: { '@_unit': 'hg', '#text': 3000},
autopilot_ratio: '',
},
power: {
number_of_engines: '',
},
geometrical: {
payload: { '@_unit': 'kg' },
design_approach: { target: '' },
},
},
},
}
I understand that it has to be a recursive function. I tried to write the following function but I don't know how to prevent nested objects from being inserted multiple times
const updateObject = (json: any, searchKey: string, unit: string, value: number): Object => {
return Object.keys(json).map((key: string) => {
if (key !== searchKey && typeof json[key] !== 'string') {
return updateObject(json[key], searchKey, unit, value);
} else {
if (typeof json[key] !== 'string') {
json[key]['@_unit'] = unit;
json[key]['#text'] = value;
return json;
} else {
return json;
}
}
});
};
console.dir(updateObject(json, 'payload', 'hg', 3000), { depth: null });
Among other things, this changes all the payload instances, it would also be useful to pass requirements.general_info.aircraft.payload as searchKey so as to change only the desired one
EDIT
The object { '@_unit': 'kg' } has a fixed format and I can already know a priori that it will be { '@_unit': 'hg', '#text': 3000} the problem is but replace it in the right place of the JSON because it is not unique, otherwise a JSON.parse(JSON.stringify(json).replace() would have been enough.
payloadonly appears at a single level in the object tree (as a child of a child of a child ofrequirements). You don't need a recursive function if that's the case.requirements.general_info.aircraft.payload) you could use something like JSONPath to get the correct object. If you don't have the full path, you do you determine, whether to update or not a certainpayloadobject (ie you want to update thepayloadof theaircraftobject but not of thegeometrical