3

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.

Ori Drori
  • 183,571
  • 29
  • 224
  • 209
Adel
  • 3,542
  • 8
  • 30
  • 31
  • It is not a duplicate! – Adel Oct 05 '17 at 14:38
  • Then you need to explain your problem better, because it sure looks like a duplicate currrently – The Archetypal Paul Oct 05 '17 at 16:12
  • 1
    @TheArchetypalPaul - he's filtering the properties of an object, not objects in an array. – Ori Drori Oct 05 '17 at 17:28
  • @OriDrori, OK so that's a possible interpretation, but given he's also saying he wants to use `filter()`, not the only one. In either case, an edit to clarify the question would have been preferable to just declaring it wasn't a duplicate. – The Archetypal Paul Oct 05 '17 at 17:31
  • 1
    And that's still a duplicate of a different question: https://stackoverflow.com/questions/44439907/filtering-out-specific-keys-in-an-object and also answered in this one https://stackoverflow.com/questions/35370646/filtering-object-by-keys-in-lodash (and probably others) – The Archetypal Paul Oct 05 '17 at 17:33

1 Answers1

5

Use Object.entries() to convert the object to an array of [key, value] tuples. Filter the tuples by check if the value is true. Convert back to an object using Object.fromEntries():

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

const result = Object.fromEntries(
  Object
    .entries(obj)
    .filter(([, val]) => val !== true)
);

console.log(result);

Old answer:

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);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209