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?
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?
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);
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']
const o = {
"1": true,
"2": false,
"3": true
};
const result = Object.entries(o).reduce((p, [k, v]) => v ? [...p, +k] : p, []);
console.log(result);
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);