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
Release: 2024-12-02 13:13:15
Original
843 people have browsed it

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));
Copy after login
// Mutate the object in place (not recommended)
Object.keys(obj).forEach((k) => obj[k] == null && delete obj[k]);
Copy after login

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] }), {});
Copy after login
// Mutate the object in place (not recommended)
Object.keys(obj)
  .filter((k) => obj[k] != null)
  .forEach((k) => delete obj[k]);
Copy after login

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template