0

I have a javascript object like {"1":true,"2":false,"3":true}

I want to create a javascript array like [1,3] by taking the keys whose value is true.

How can I do that?

3
  • 2
    @VipinKumar, reopened even before posting your comment. And this not exact duplicate but OP could have used that answer to find his solution. Commented Dec 7, 2017 at 11:14
  • Totally agree with you. I too figured that out. Once i submitted the comment, duplicate was removed. Commented Dec 7, 2017 at 11:17
  • @VipinKumar, Once i submitted the comment, duplicate was removed. then you too could have removed the comment Commented Dec 7, 2017 at 11:32

4 Answers 4

2

Use Object#keys with array#filter to return those key whose value is true.

var obj = {"1":true,"2":false,"3":true};
var result = Object.keys(obj).filter(k => obj[k]).map(Number);
console.log(result);

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

Comments

1

You can do that Out of the box from ES5 using Object.keys(yourobject) and using the filter on top of it

var obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.keys(obj)); // console: ['0', '1', '2']

Check it out here MDN article

Comments

1

Please find the solution below. First you need to filter and then map to Numbers.

var obj = {
  "1": true,
  "2": false,
  "3": true
}

var keys = Object.keys(obj).filter(key => obj[key]).map(key => Number(key))

console.log(keys);

Comments

1

const o = {
    "1": true,
    "2": false,
    "3": true
};
const result = Object.entries(o).reduce((p, [k, v]) => v ? [...p, +k] : p, []);
console.log(result);

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.