Delete false values ​​in object

The problem I ran into is removing values ​​in onject that has false property Here is the object

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

I can get the values ​​in an array using the following logic:

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

+8
javascript arraylist arrays angularjs
source share
5 answers

I just created a solution to your problem in JSBin: Working demo

Enter 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 questions.

+3
source share

You have the keys of the object in the array. Run the filter above 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"] 
+6
source share

To remove these properties, you can use this algorithm:

 for (k in myObj) { if (myObj.hasOwnProperty(k) && myObj[k] === false) { delete myObj[k]; } } 

If you are only interested in non- false keys, you can use:

 var keys = Object.keys(myObj).filter(function (k) { return myObj[k] !== false; }); 

Checking hasOwnProperty() necessary because objects may contain properties other than the user (for example, prototype ) that you really don't want to communicate with.

+1
source share

You need to iterate over the object using a for...in loop

 var myObj={105:true,183:false,108:true,106:false} for(var key in myObj){ if(myObj.hasOwnProperty(key) && myObj[key] == false){ delete myObj[key]; } } console.log(JSON.stringify(myObj)) //{"105":true,"108":true} console.log(Object.keys(myObj)) //["105", "108"] 
+1
source share

You can also use this NPM package or import this open source object-clean , which clears all properties of the object that contain the fake value and returns a new object without them.

Example:

 clean({ foo: null, bar: 'foo' }) // => { bar: 'foo' } 
+1
source share

All Articles