We are facing a challenge in our company with the editing form. One of our team members unilaterally changed the format of the API payload return, causing us to fall behind and play catchup.
Unfortunately, the API calls we need to make do not support nested objects, so I have to flatten the structure in order to manipulate and submit the values.
This is the new nested structure:
{
"status": 1,
"data" : {
"name": "Tank",
"dimensions": "2.0 x 2.5 x 4.0"
}
}
I need to convert it back to something like this:
{
"status": 1,
"name": "Tank",
"dimensions": "2.0 x 22.5 x 4.0"
}
Despite finding various solutions online, I keep encountering the same TypeScript error:
"for (... in ...) statements must be filtered with an if statement"
I've noticed that many of these solutions mistakenly embed the name of the first element in front of its nested elements, resulting in a more complex object structure like this:
{
"status": 1,
"data.name": "Tank",
"data.dimensions": "2.0 x 22.5 x 4.0"
}
If anyone can guide me on how to rewrite the flatten function to eliminate the TypeScript error and avoid appending the first level element's name to its nested elements, maintaining a simple single-level object structure, I would greatly appreciate it.
Below is my current flatten function:
const obj = values;
const flattenObj = (ob) => {
// The object which contains the final result
const result = {};
// loop through the object "ob"
for (const i in ob) {
// We check the type of the i using typeof() function and recursively call the function again
if ((typeof ob[i]) === 'object' && !Array.isArray(ob[i])) {
const temp = flattenObj(ob[i]);
for (const j in temp) {
// Store temp in result
result[i + '.' + j] = temp[j];
}
}
// Else store ob[i] in result directly
else {
result[i] = ob[i];
}
}
return result;
};
console.log(flattenObj(ob));