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

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

Patricia Arquette
Patricia ArquetteOriginal
2024-11-28 04:31:13298browse

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

Remove Blank Attributes from an Object in JavaScript

In JavaScript, objects can have properties that are undefined or null, which can clutter up code and make it more difficult to work with. To remedy this, we can remove these blank attributes from an object using various techniques.

ES10/ES2019

These methods use the introduction of the Object.fromEntries() method:

  • A one-liner: let o = Object.fromEntries(Object.entries(obj).filter(([_, v]) => v != null));
  • Same as above but as a function: function removeEmpty(obj) { return Object.fromEntries(Object.entries(obj).filter(([_, v]) => v != null)); }
  • A recursive version to remove items from nested objects: 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

  • A mutating one-liner: Object.keys(obj).forEach((k) => obj[k] == null && delete obj[k]);
  • A non-mutating version: let o = Object.keys(obj) .filter((k) => obj[k] != null) .reduce((a, k) => ({ ...a, [k]: obj[k] }), {});
  • Similar to above, written as a function: function removeEmpty(obj) { return Object.entries(obj) .filter(([_, v]) => v != null) .reduce((acc, [k, v]) => ({ ...acc, [k]: v }), {}); }
  • A recursive function to handle nested objects: 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

  • A functional non-recursive version: function removeEmpty(obj) { return Object.keys(obj) .filter(function (k) { return obj[k] != null; }) .reduce(function (acc, k) { acc[k] = obj[k]; return acc; }, {}); }
  • A recursive functional version: 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 Remove Null or Undefined Attributes from a JavaScript Object?. 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