Home > Web Front-end > JS Tutorial > How Can I Remove Null and Undefined Attributes from a JavaScript Object?

How Can I Remove Null and Undefined Attributes from a JavaScript Object?

DDD
Release: 2024-12-02 00:53:10
Original
710 people have browsed it

How Can I Remove Null and Undefined Attributes from a JavaScript Object?

Remove Empty Attributes from an Object in JavaScript

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.

Overview

To remove all attributes which are undefined or null in a JavaScript object, you can use the following approaches:

Iterative (Functional Style)

  1. ES10/ES2019 Example:

    let o = Object.fromEntries(Object.entries(obj).filter(([_, v]) => v != null));
    Copy after login
  2. ES6/ES2015 Example:

    let o = Object.keys(obj)
      .filter((k) => obj[k] != null)
      .reduce((a, k) => ({ ...a, [k]: obj[k] }), {});
    Copy after login

Iterative (Imperative Style)

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

Recursive

  1. 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])
      );
    }
    Copy after login

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template