1

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"]

4 Answers 4

4

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);

Sign up to request clarification or add additional context in comments.

2 Comments

I would suggest not using implicit type-casting. Use strict comparison instead: filter(k => object[k] === true). It will only catch true values.
op has only true/false values. why strict comparison if truty works?
2

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)

Comments

1

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);

Comments

1

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.