Home >Web Front-end >JS Tutorial >How Can I Remove Null and Undefined Attributes from a JavaScript Object?
JavaScript object properties can sometimes contain undefined or null values. This can lead to difficulties when working with data and can make it challenging to maintain consistency and accuracy. Removing these empty attributes can be beneficial for optimizing code and improving data integrity.
To remove all attributes which are undefined or null in a JavaScript object, you can use the following approaches:
ES10/ES2019 Example:
let o = Object.fromEntries(Object.entries(obj).filter(([_, v]) => v != null));
ES6/ES2015 Example:
let o = Object.keys(obj) .filter((k) => obj[k] != null) .reduce((a, k) => ({ ...a, [k]: obj[k] }), {});
ES10/ES2019 Example:
function removeEmpty(obj) { const newObj = {}; Object.entries(obj).forEach(([k, v]) => { if (v === Object(v)) { newObj[k] = removeEmpty(v); } else if (v != null) { newObj[k] = obj[k]; } }); return newObj; }
ES10/ES2019 Example:
function removeEmpty(obj) { return Object.fromEntries( Object.entries(obj) .filter(([_, v]) => v != null) .map(([k, v]) => [k, v === Object(v) ? removeEmpty(v) : v]) ); }
The above is the detailed content of How Can I Remove Null and Undefined Attributes from a JavaScript Object?. For more information, please follow other related articles on the PHP Chinese website!