duskdeep duskdeep - 3 months ago 14
jQuery Question

JS or jQuery how to delete key-value pair

Using JS or jQuery how to delete the key-value pair which the value is of type “

Null
” &
""
.
e.g.
before:

Object {style: "fruit", origin: "Thailand", day: "18d", color: "", weight: null}


alter:

Object {style: "fruit", origin: "Thailand", day: "18d"}

Answer

There are two parts to this:

  1. Loop through the object's properties

  2. Remove a property from an object

There are lots of ways to do the first, covered by this question's answers. Assuming you only care about "own" (non-inherited) properties, I'd probably use Object.keys to get an array of property names and then loop that.

The second is done with the delete operator.

So:

Object.keys(theObject).forEach(function(key) {
    var value = theObject[key];
    if (value === "" || value === null) {
        delete theObject[key];
    }
});

Live Example:

var theObject = {
  style: "fruit",
  origin: "Thailand",
  day: "18d",
  color: "",
  weight: null
};
console.log("Before:", JSON.stringify(theObject, null, 2));
Object.keys(theObject).forEach(function(key) {
  var value = theObject[key];
  if (value === "" || value === null) {
    delete theObject[key];
  }
});
console.log("After:", JSON.stringify(theObject, null, 2));