Go through Object, filter by field and do javascript push

2

I have the following object, for example:

{
"name":"false",
"var_RadiacionGlobalInt":true,
"var_CO2InvVaisala":true,
"var_RadiacionExt":false,
"var_VVExt":false
}

I would need to go through that object and the elements that are true to add them to a new array with a push. This is the code that I have implemented:

public guardar(){
    this.checkboxsensores = [];
    for (let variable in this.checkbox) {
        if (variable === 'true') {
            this.checkboxsensores.push(variable);
        }
    }
}

I need a final format like this:

["var_RadiacionGlobalInt", "var_CO2InvVaisala"]

I can not search by the value true only by the name of the field, how can I filter by Booleans?

Greetings.

    
asked by Manolait 25.07.2018 в 20:38
source

2 answers

2

Dev. Joel's answer is better, but for you to understand what is wrong with your code, you have to verify the value of the property and not the name of the property itself. Your corrected code would be like this:

var checkbox = {"name":"false","var_RadiacionGlobalInt":true,"var_CO2InvVaisala":true,"var_RadiacionExt":false,"var_VVExt":false};

function guardar(){
    var checkboxsensores = [];
    for (let variable in checkbox) {         
       if (checkbox[variable] === true) {
         checkboxsensores.push(variable);
       }
    }
    console.log(checkboxsensores);
}
guardar();
    
answered by 25.07.2018 / 20:50
source
3

One option would be to use Object.keys to get the properties of the object and then filter using filter () will create a new array with properties that have the value true obj[el]===true

let obj ={"name":"false","var_RadiacionGlobalInt":true,"var_CO2InvVaisala":true,"var_RadiacionExt":false,"var_VVExt":false};
let arr = Object.keys(obj).filter(el=> obj[el]===true);
console.log(arr);
    
answered by 25.07.2018 в 20:45