如何使用下划线从对象中的数组中删除空的,null,未定义的值

时间:2016-02-24 14:19:06

标签: javascript jquery underscore.js

我想删除与null关联的所有键,我尝试使用_.filter,_.compact,_.reject,但没有什么对我有用,使用最新版本的下划线1.8.3

这就是我的尝试:

_.reject(Obj,function (value) {
    return value===null;
})

_.compact(Obj)

对象:

    var Obj =  {
  "pCon": [
    {
      "abc": null,
      "def": null,
      "ghi": {
        "content": "abc"
      }
    },
    {
      "abc": null,
      "def": {
        imgURL: "test.png"
      },
      "ghi": null
    },
    {
      "abc": {
        "key": "001"
      },
      "def": null,
      "ghi": null
    }
  ]
}

3 个答案:

答案 0 :(得分:2)

以递归样式在纯Javascript中的解决方案。



function deleteNull(o) {
    if (typeof o === 'object') {
        Object.keys(o).forEach(function (k) {
            if (o[k] === null) { // or undefined or '' ...?
                delete o[k];
                return;
            }
            deleteNull(o[k]);
        });
    }
}

var object = { "pCon": [{ "abc": null, "def": null, "ghi": { "content": "abc" } }, { "abc": null, "def": { imgURL: "test.png" }, "ghi": null }, { "abc": { "key": "001" }, "def": null, "ghi": null }] };

deleteNull(object);
document.write('<pre>' + JSON.stringify(object, 0, 4) + '</pre>');
&#13;
&#13;
&#13;

答案 1 :(得分:1)

 for (var i in Obj["pCon"]) {
  if (Obj["pCon"][i]["abc"] === null || Obj["pCon"][i]["abc"] === undefined) {
  // test[i] === undefined is probably not very useful here
    delete Obj["pCon"][i]["abc"];
  }
  if (Obj["pCon"][i]["def"] === null || Obj["pCon"][i]["def"] === undefined) {
  // test[i] === undefined is probably not very useful here
    delete Obj["pCon"][i]["def"];
  }
  if (Obj["pCon"][i]["ghi"] === null || Obj["pCon"][i]["ghi"] === undefined) {
  // test[i] === undefined is probably not very useful here
    delete Obj["pCon"][i]["ghi"];
  }
}

它适用于jsfiddle https://jsfiddle.net/3wd7dmex/1/

答案 2 :(得分:0)

这是使用下划线的解决方案。请注意,这不会像Nina的解决方案那样递归地深入到结构中。但是如果需要,你可以扩展它以反映这种行为。

var obj = {
  "pCon": [{
    "abc": null,
    "def": null,
    "ghi": {
      "content": "abc"
    }
  }, {
    "abc": null,
    "def": {
      imgURL: "test.png"
    },
    "ghi": null
  }, {
    "abc": {
      "key": "001"
    },
    "def": null,
    "ghi": null
  }]
};
var result = _.chain(obj).map(function(value, key) {
  value = _.map(value, function(singleObj) {
    return _.pick(singleObj, _.identity) // pick the keys where values are non empty
  });
  return [key, value];
}).object().value();

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>