This solution is generated by ChatGPT, correctness is not guaranteed.
AI solution for JavaScript Coding Question on BFE.dev
176. undefined to null
Here's a possible solution:
function undefinedToNull(obj: any): any {
if (Array.isArray(obj)) {
return obj.map(elem => undefinedToNull(elem));
} else if (typeof obj === 'object' && obj !== null) {
const newObj = {};
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
newObj[key] = undefinedToNull(obj[key]);
}
}
return newObj;
} else {
return obj === undefined ? null : obj;
}
}
The function checks if the input is an array, an object or a primitive value, and treats each case accordingly. If it's an array, it maps over each element, recursively calling undefinedToNull
on them. If it's an object, it creates a new object and iterates over its properties, recursively calling undefinedToNull
on each value. If it's a primitive value, it returns either null if the value is undefined, or the value itself otherwise.
Note that this implementation assumes that the input is a valid JSON object or array (i.e. no circular references, no functions, no symbol properties, etc.). If the input is a more general object, it might need additional checks or custom handling.