Removing Blank Attributes from Objects in JavaScript
Many times, when working with objects, it's necessary to remove all attributes that are undefined or null. This helps maintain data integrity and prevent errors when accessing properties.
ES10/ES2019 Solutions
// Return a new object without blank attributes let o = Object.fromEntries(Object.entries(obj).filter(([_, v]) => v != null));
// Mutate the object in place (not recommended) Object.keys(obj).forEach((k) => obj[k] == null && delete obj[k]);
ES6/ES2015 Solutions
// Return a new object with blanks removed let o = Object.keys(obj) .filter((k) => obj[k] != null) .reduce((a, k) => ({ ...a, [k]: obj[k] }), {});
// Mutate the object in place (not recommended) Object.keys(obj) .filter((k) => obj[k] != null) .forEach((k) => delete obj[k]);
ES5/ES2009 Solutions
function removeEmpty(obj) { const newObj = {}; for (let prop in obj) { if (obj.hasOwnProperty(prop) && obj[prop] != null) { newObj[prop] = obj[prop]; } } return newObj; }
The above is the detailed content of How to Efficiently Remove Null or Undefined Attributes from JavaScript Objects?. For more information, please follow other related articles on the PHP Chinese website!