Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove false values in object

The problem that I'm facing is -removing the values in the onject that has the property false Here is the object

var myObj={105:true,183:false,108:true,106:false}

I'm able to get the values in an array by using the following logic:

Object.keys(myObj) gives ["105","183","108","106"] But I need a way to remove the values that have the property false and generate as ["105",108"].Can you help me out ?

like image 855
forgottofly Avatar asked Jun 01 '15 10:06

forgottofly


2 Answers

You have the keys of the object in an array. Run filter over it.

var myObj={105:true,183:false,108:true,106:false};

var result = Object.keys(myObj).filter(function(x) { 
    return myObj[x] !== false; 
});
// result = ["105", "108"]
like image 77
UltraInstinct Avatar answered Sep 29 '22 01:09

UltraInstinct


I've just created a solution to your problem on JSBin: Working Demo

Please find below the code:

var myObj={105:true,183:false,108:true,106:false};
var myArray = [];

function RemoveFalseAndTransformToArray () {
  for (var key in myObj) {
    if(myObj[key] === false) {
        delete myObj[key];
    } else {
        myArray.push(key);
    }
  }
}
RemoveFalseAndTransformToArray();
console.log("myObj: ", myObj);
console.log("myArray: ", myArray);
// result = ["105", "108"]

Please, let me know if you have any question.

like image 23
julien bouteloup Avatar answered Sep 29 '22 00:09

julien bouteloup