0

I have an object with few properties true/false, I need to return an array with only the property name with true.

I have tried Object.entries but not sure how to create an array now.

const inputs = {
  a: true,
  b: true,
  c: false
}


// result should be ['a','b']

// i have tried so far this one with no success
// const result = Object.entries(inputs).map((x, idx) => console.log(x))
1
  • 4
    Try Object.keys(inputs).filter(key => inputs[key]); Commented Aug 8, 2018 at 15:18

3 Answers 3

5
Object.keys(inputs).filter(key => inputs[key])
Sign up to request clarification or add additional context in comments.

Comments

0

Use my JSFiddle for the code.

Use the filter array method, described by MDN as

creates a new array with all elements that pass the test implemented by the provided function

Call it on the Object.keys, a built in array for objects:

returns an array of a given object's property names

Source: Object.keys()

So, to put it together, it would look like

const inputs = {
 a: true,
 b: true,
 c: false
}
console.log(inputs); // Output: {a: true, b: true, c: false}

const arr = Object.keys(inputs).filter(keyName => inputs[keyName]);
console.log(arr); // Output: ["a", "b"]

Comments

0

For give only keys of object use filter:

Like this:

const inputs = {
  a: true,
  b: true,
  c: false
};

var true_inputs = Object.keys(inputs).filter(key => inputs[key]);
console.log(true_inputs);

Or Jquery map:

const inputs = {
  a: true,
  b: true,
  c: false
};


var true_inputs = $.map(inputs, function(n, i) { if(n) return i });
console.log(true_inputs);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

For to get the whole object use for .. in: Like this:

const inputs = {
  a: true,
  b: true,
  c: false
};


var true_inputs = {};

for(var key in inputs){
	if(inputs[key])
	  true_inputs[key]=inputs[key];
}

console.log(inputs);
console.log(true_inputs);

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.