![](/img/trans.png)
[英]How to remove a property from an object and/or array if the value is null, undefined or empty?
[英]How to remove empty,null, undefined values from array within object using underscore
我想删除与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
}
]
}
递归样式的纯Java解决方案。
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>');
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/
这是使用下划线的解决方案。 请注意,这不会像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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.