If any pre-defined keys have an empty string value, I want to replace it with a null value.
For example:
const foo = {
first: '',
second: 'bar',
third: '',
fourth: '',
fifth: '',
}
Should be updated to:
const foo = {
first: null,
second: 'bar',
third: '',
fourth: null,
fifth: '',
}
Now we can use the following function successfully:
const normalize = (payload, keys) => {
const clone = { ...payload }
Object.entries(payload).forEach(([key, value]) => {
if (keys.includes(key) && value === '') {
clone[key] = null;
}
});
return clone;
}
const foo = {
first: '',
second: 'bar',
third: '',
fourth: '',
fifth: '',
}
console.log(normalize(foo, ['first', 'third']));
However, the 'clone' variable could be improved.
One common method for this is using Object.assign().
Would you like to explore this approach?