asdfboy
asdfboy

Reputation: 59

Push Objects Key in Array when Value is True

My object look like this

{
 Key1: true,
 Key2: false,
 Key3: false,
 Key4: true
}

How to save the Keys which are true in an Array like this:

["Key1", "Key4"]

Upvotes: 1

Views: 1165

Answers (4)

Andre Pena
Andre Pena

Reputation: 59336

Using the filter function.

var myObject = {
 Key1: true,
 Key2: false,
 Key3: false,
 Key4: true
}

var myFilteredArray = myObject.keys().filter(function(key) { return myObject[key] }

console.log(myFilteredArray); // ["Key1", "Key4"]

explaination

  • myObject.keys() returns the keys of the object as an array.
  • The Array filter function receives a function that is executed for each element, if that function returns true, that element is selected. The resulting array is composed of only items that have been "selected"

Upvotes: 1

Jatin patil
Jatin patil

Reputation: 4288

var keys = {
 Key1: true,
 Key2: false,
 Key3: false,
 Key4: true
}

var filteredKeys = [];

for(var key in keys) {
  if(keys[key] == true) {
    filteredKeys.push(key);
  }
}
console.log(filteredKeys);

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386654

You could filter the keys.

var object = { Key1: true, Key2: false, Key3: false, Key4: true },
    trueKeys = Object.keys(object).filter(k => object[k]);

console.log(trueKeys);

Upvotes: 4

Nenad Vracar
Nenad Vracar

Reputation: 122047

You can get keys with Object.keys() and then use filter()

var obj = {
  Key1: true,
  Key2: false,
  Key3: false,
  Key4: true
}

var keys = Object.keys(obj).filter(e => obj[e] === true);
console.log(keys)

Upvotes: 2

Related Questions