Remove Null Values from an Object in Javascript-Code Examples

Radu TM

Remove Null Values from an Object in Javascript

JavaScript by Radu TM June 21, 2022

const obj = {
  name: 'John',
  age: null,
  job: 'teacher',
  city: null
};

// use for loop
for (let key in obj) {
  if (obj[key] === null) {
    delete obj[key];
  }
}

// use Object.keys()
const obj = {
  name: 'John',
  age: null,
  job: 'teacher',
  city: null
};

const newObj = Object.keys(obj).reduce((acc, key) => {
  if (obj[key]) {
    acc[key] = obj[key];
  }
  return acc;
}, {});

console.log(newObj); // { name: 'John', job: 'teacher' }

0

21.280

Remove Null Values from an Object in Javascript

JavaScript by Radu TM June 21, 2022

const obj = {
  foo: '🍎',
  bar: '🍌',
  baz: null,
  qux: undefined,
};

// iterate over the object's own enumerable properties
for (const key of Object.keys(obj)) {
  // if the property's value is null, delete it
  if (obj[key] === null) {
    delete obj[key];
  }
}

console.log(obj);
// { foo: '🍎', bar: '🍌' }

0

21.280

Remove Null and Undefined Values from Object in JavaScript

JavaScript by Radu TM June 21, 2022

const removeNullAndUndefinedValuesFromObject = obj => {
  // return a new object with only the truthy values
  return Object.keys(obj)
    .filter(key => obj[key])
    .reduce((acc, key) => {
      // copy each truthy value to the new object
      acc[key] = obj[key];
      return acc;
    }, {});
};

// given this object
const obj = {
  a: 1,
  b: null,
  c: undefined,
  d: 'hi'
};

console.log(removeNullAndUndefinedValuesFromObject(obj));
// { a: 1, d: 'hi' }

0

14.783

Remove Null and Undefined Values from Object in JavaScript

JavaScript by Radu TM June 21, 2022

const removeNullAndUndefinedValues = (obj) => {
  // create a new object to store the values in
  const newObj = {};
  // loop over each key/value pair in the passed in object
  for (const [key, value] of Object.entries(obj)) {
    // if the value is not null or undefined, add it to the new object
    if (value !== null && value !== undefined) {
      newObj[key] = value;
    }
  }
  // return the new object
  return newObj;
};

0

14.783

Related JavaScript Queries

Latest JavaScript Queries

Explore code examples by categories