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?

Saswat
  • 12,320
  • 16
  • 77
  • 156
  • 2
    @VipinKumar, reopened even before posting your comment. And this not exact duplicate but OP could have used that answer to find his solution. – Satpal Dec 07 '17 at 11:14
  • Totally agree with you. I too figured that out. Once i submitted the comment, duplicate was removed. – Vipin Kumar Dec 07 '17 at 11:17
  • @VipinKumar, _Once i submitted the comment, duplicate was removed._ then you too could have removed the comment – Satpal Dec 07 '17 at 11:32

4 Answers4

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);
Satpal
  • 132,252
  • 13
  • 159
  • 168
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
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

Sagar Pudi
  • 4,634
  • 3
  • 32
  • 51
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);
Ben Aston
  • 53,718
  • 65
  • 205
  • 331
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);
Vipin Kumar
  • 6,441
  • 1
  • 19
  • 25