EN
JavaScript - removing undefined fields from object
1
answers
0
points
How can I remove properties from object that are undefined or null?
1 answer
0
points
Quick solution (ES6+):
const newObject = Object.fromEntries(Object.entries(myObject).filter(([_, value]) => value != null));
Reusable arrow function
// ONLINE-RUNNER:browser;
const removeBlank = (inputObject) => {
return Object.fromEntries(
Object.entries(inputObject).filter(([_, value]) => value != null)
);
}
// Usage example:
const myObject = { a: 1, b: '', c: undefined, d: null };
const newObject = removeBlank(myObject);
console.log(JSON.stringify(newObject)); // { a: 1, b: '' }
Explanation:
To remove properties that are undefined or null we used the following methods:
Object.entries()- to get array of a given object's properties ([key, value]pairs),filter()- to remove properties that values arenullorundefined,Object.fromEntries()- to create a new result object from filtered[key, value]pairs.
Recursion to remove properties from nested objects
// ONLINE-RUNNER:browser;
const removeBlank = (inputObject) => {
return Object.fromEntries(
Object.entries(inputObject)
.filter(([_, value]) => value != null)
.map(([key, value]) => [
key,
value === Object(value) ? removeBlank(value) : value,
])
);
};
// Usage example:
const myObject = {
a: 1,
b: { b1: undefined },
c: { c1: null },
};
const newObject = removeBlank(myObject);
console.log(JSON.stringify(newObject, null, 4)); // { a: 1, b: {}, c: {} }
References
0 comments
Add comment