I am in need of modifying a TypeScript object by conducting a key search. It is important to note that the key may be repeated within the object, so I must ensure it belongs to the correct branch before making modifications to the corresponding object. To illustrate, consider the following initial object:
{
requirements: {
general_info: {
aircraft: {
payload: { '@_unit': 'kg' },
autopilot_ratio: '',
},
power: {
number_of_engines: '',
},
geometrical: {
payload: { '@_unit': 'kg' },
design_approach: { target: '' },
},
},
},
}
After modification, the object should appear as follows:
{
requirements: {
general_info: {
aircraft: {
payload: { '@_unit': 'hg', '#text': 3000},
autopilot_ratio: '',
},
power: {
number_of_engines: '',
},
geometrical: {
payload: { '@_unit': 'kg' },
design_approach: { target: '' },
},
},
},
}
A recursive function is necessary to achieve this. I have attempted to write a function for this purpose, but I am facing difficulties in preventing 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 });
Additionally, it would be beneficial to pass
requirements.general_info.aircraft.payload
as the searchKey in order to modify only the desired instance.
EDIT
The format of the object { '@_unit': 'kg' }
is predetermined and I already know in advance that it will be replaced with { '@_unit': 'hg', '#text': 3000}
. The challenge lies in replacing it at the correct position within the JSON structure, as it is not a distinct occurrence. A simple
JSON.parse(JSON.stringify(json).replace()
operation would not suffice in this scenario.