Home >Web Front-end >JS Tutorial >How to Efficiently Remove Null or Undefined Attributes from JavaScript Objects?

How to Efficiently Remove Null or Undefined Attributes from JavaScript Objects?

Linda Hamilton
Linda HamiltonOriginal
2024-12-02 13:13:15957browse

How to Efficiently Remove Null or Undefined Attributes from JavaScript Objects?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn