JS或jQuery如何删除键值对

时间:2016-09-04 07:05:23

标签: javascript jquery object key-value

使用JS或jQuery如何删除值为“Null”的键值对& ""。 例如 之前:

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

改变:

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

5 个答案:

答案 0 :(得分:1)

这有两个部分:

  1. 循环浏览对象的属性

  2. 从对象中删除属性

  3. 有很多方法可以做到第一个,由this question's answers覆盖。假设你只关心"拥有" (非继承)属性,我可能会使用Object.keys来获取一个属性名称数组,然后循环它。

    第二个是使用delete运算符完成的。

    所以:

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

    直播示例:

    
    
    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));
    
    
    

答案 1 :(得分:1)

您可以使用for..in完成循环,找到哪个密钥有null""

然后使用delete删除密钥

var myObj = {
  style: "fruit",
  origin: "Thailand",
  day: "18d",
  color: "",
  weight: null
}

for(var keys in myObj){
 if(myObj[keys] ===null || myObj[keys] === ""){
  delete myObj[keys]
 }
}
console.log(myObj)

JSFIDDLE

答案 2 :(得分:0)

通过迭代抛出对象的键并在结果数组中推送匹配属性的简单解决方案:

var input = {style: "fruit", origin: "Thailand", day: "18d", color: "", weight: null};
var keys = Object.keys(input);
var result = {};
keys.forEach(key => {if (input[key] != null && input[key] != "") result[key] = input[key]});
console.log(result); // { style: 'fruit', origin: 'Thailand', day: '18d' }

答案 3 :(得分:-1)

var yourObj={style: "fruit", origin: "Thailand", day: "18d", color: "", weight: null}

for(var attr in yourObj){
  if(!yourObj[attr]){
    delete yourObj[attr]
  }
}

答案 4 :(得分:-1)

可以使用以下代码完成:

var map = {style: "fruit", origin: "Thailand", day: "18d", color: "", weight: null};

for (var i in map){
    if(map[i]==null || map[i]==""){
       delete(map[i]);
 }
}