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 ?

Answers:

Answer

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.

Answer

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"]
Answer

To remove those properties you can use this algorithm:

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

If you are just interested in the keys of non-false values, you can use:

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

The hasOwnProperty() check is necessary because objects may contain non-user properties (such as prototype) which you really don't want to mess with.

Answer

You need to iterate over the object using 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"]

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.