Home >Web Front-end >JS Tutorial >How can I efficiently remove null and undefined attributes from JavaScript objects?

How can I efficiently remove null and undefined attributes from JavaScript objects?

Linda Hamilton
Linda HamiltonOriginal
2024-12-26 00:33:10702browse

How can I efficiently remove null and undefined attributes from JavaScript objects?

Removing Blank Attributes from JavaScript Objects

When dealing with data objects, it's often necessary to remove attributes that are not defined or set to null. This article provides solutions for this problem using various JavaScript versions and techniques.

ES10/ES2019 Solutions

One-Liner with Object.fromEntries

let o = Object.fromEntries(Object.entries(obj).filter(([_, v]) => v != null));

Function Using Object.fromEntries and Recursion

function removeEmpty(obj) {
  return Object.fromEntries(
    Object.entries(obj)
      .filter(([_, v]) => v != null)
      .map(([k, v]) => [k, v === Object(v) ? removeEmpty(v) : v])
  );
}

ES6/ES2015 Solutions

One-Liner with Mutation

Object.keys(obj).forEach((k) => obj[k] == null && delete obj[k]);

Single Declaration Without Mutation

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

Function with Recursion

function removeEmpty(obj) {
  return Object.entries(obj)
    .filter(([_, v]) => v != null)
    .reduce((acc, [k, v]) => ({ ...acc, [k]: v === Object(v) ? removeEmpty(v) : v }), {});
}

ES5/ES2009 Solutions

Non-Recursive Functional Style

function removeEmpty(obj) {
  return Object.keys(obj)
    .filter(function (k) {
      return obj[k] != null;
    })
    .reduce(function (acc, k) {
      acc[k] = obj[k];
      return acc;
    }, {});
}

Non-Recursive Imperative Style

function removeEmpty(obj) {
  const newObj = {};
  Object.keys(obj).forEach(function (k) {
    if (obj[k] && typeof obj[k] === "object") {
      newObj[k] = removeEmpty(obj[k]);
    } else if (obj[k] != null) {
      newObj[k] = obj[k];
    }
  });
  return newObj;
}

Recursive Functional Style

function removeEmpty(obj) {
  return Object.keys(obj)
    .filter(function (k) {
      return obj[k] != null;
    })
    .reduce(function (acc, k) {
      acc[k] = typeof obj[k] === "object" ? removeEmpty(obj[k]) : obj[k];
      return acc;
    }, {});
}

The above is the detailed content of How can I efficiently remove null and 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