ES6 - Filter an Object based on True values

Viewed 5183

I have an Object which contains some booleans like this:

{ date: "2017-10-05", name_change: false, age_change: true, ... }

I want to filter() the keys which are true. I also need the date value. how can I make this filter?

Regards.

1 Answers

Get the keys with Object#keys, and then iterate the array of keys with Array#reduce, and build a new object that doesn't contain keys which value equals to true:

const obj = { 
  date: "2017-10-05", 
  name_change: false, 
  age_change: true 
};

const result = Object.keys(obj)
  .reduce((o, key) => {
    obj[key] !== true && (o[key] = obj[key]);

    return o;
  }, {});

console.log(result);

Related