Filtering object properties based on value

Here are two vanilla javascript options:

A.: Iterate over the object’s keys and delete those having a falsey value.

var obj = {
  propA: true,
  propB: true,
  propC: false,
  propD: true,
};

Object.keys(obj).forEach(key => {
  if (!obj[key]) delete obj[key];
});

console.log(obj);

See Object.keys() and Array.prototype.forEach()

B.: Iterate over the object’s keys and add truthy values to a new object.

var obj = {
  propA: true,
  propB: true,
  propC: false,
  propD: true,
};

var filteredObj = Object.keys(obj).reduce((p, c) => {    
  if (obj[c]) p[c] = obj[c];
  return p;
}, {});

console.log(filteredObj);

See Object.keys() and Array.prototype.reduce()

Leave a Comment