i wish to make a utility function – which takes in an input – vanilla plain object – such that – it recursively traverses it to the deepest level even if a value is an array, it should iterate over its individual elements and for each array value’s element or field’s value- it checks –
- if the currently iterated value is nullish (null or undefined) – it make the value "NULL_VALUE" as a string,
- if the currently iterated value is empty string (""), then it makes the value "EMPTY_VALUE" as a string,
- if the currently iterated value is empty array ( [] ), then it makes the value "EMPTY_ARRAY" as a string,
- if the currently iterated value is object array ( { } ), then it makes the value "EMPTY_OBJECT" as a string,
- and finally if its any value other than above then the value is made "VALID_VALUE" as a string
Example
const input = {
a: null,
b: "",
c: [],
d: {},
e: "hello",
f: [null, "", [], {}, "world"],
g: {
h: null,
i: "",
j: [],
k: {},
l: "nested",
},
};
Output
{
a: "NULL_VALUE",
b: "EMPTY_VALUE",
c: "EMPTY_ARRAY",
d: "EMPTY_OBJECT",
e: "VALID_VALUE",
f: ["NULL_VALUE", "EMPTY_VALUE", "EMPTY_ARRAY", "EMPTY_OBJECT", "VALID_VALUE"],
g: {
h: "NULL_VALUE",
i: "EMPTY_VALUE",
j: "EMPTY_ARRAY",
k: "EMPTY_OBJECT",
l: "VALID_VALUE",
},
}
My current approach is as follows where for very nested object it doesnt exactly work as intended as some empty arrays and objects are skipped
const transformObject = (obj) => {
const transformedObj = {};
for (const key in obj) {
const value = obj[key];
if (Array.isArray(value)) {
transformedObj[key] = transformValue(transformArray(value));
} else if (isPlainObject(value)) {
transformedObj[key] = transformValue(transformObject(value));
} else {
transformedObj[key] = transformValue(value);
}
}
return transformedObj;
};
const transformArray = (arr: any[]): any[] => {
return arr.map((item) => {
if (isPlainObject(item)) return transformObject(item);
if (Array.isArray(item)) return transformArray(item);
return transformValue(item);
});
};
const transformValue = (value: any): any => {
if (value === null || value === undefined) return "NULL_VALUE";
if (value === "") return "EMPTY_VALUE";
if (Array.isArray(value) && value.length === 0) return "EMPTY_ARRAY";
if (isPlainObject(value) && Object.keys(value).length === 0)
return "EMPTY_OBJECT";
return value;
};
2
Answers
Here’s a similar recursive approach
Here some function,
F
, that maps the inputt
to the desired output –And here’s a TypeScript version with added input
I
and outputO
types –