Javascript 如何从JS中的数组中删除空对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33884033/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I remove empty object in from an array in JS
提问by Rudy
I have an array of objects and when I stringify, it looks like this:
我有一个对象数组,当我进行字符串化时,它看起来像这样:
"[[{"entrReqInv": "Neither"},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}]]"
How can I remove the empty {}
s?
如何删除空的{}
s?
回答by djfdev
var newArray = array.filter(value => Object.keys(value).length !== 0);
回答by Barmar
You can use Array.prototype.filter
to remove the empty objects before stringifying.
您可以使用Array.prototype.filter
在字符串化之前删除空对象。
JSON.stringify(array.filter(function(el) {
// keep element if it's not an object, or if it's a non-empty object
return typeof el != "object" || Array.isArray(el) || Object.keys(el).length > 0;
});
回答by Dude
I would recommend using the following code:
我建议使用以下代码:
var newArray = array.filter(value => JSON.stringify(value) !== '{}');
I did not use Object.keys(value).length !== 0because it not only removes empty objects { }but also removes empty arrays [ ]. If you only want to remove empty objects, use the above method.
我没有使用Object.keys(value).length !== 0因为它不仅删除空对象{ }还删除空数组[ ]。如果您只想删除空对象,请使用上述方法。
回答by user2049674
If your array of objects is like -
如果您的对象数组类似于 -
finalobj--- [ { 'patient._id': '123' },
{ 'patient.birthDate': 'lt2013-01-14', {}, {} } ]
Then use the below line to remove the blank object --
然后使用下面的行删除空白对象-
var newArray = obj.filter((value: {}) => Object.keys(value).length !== 0);
回答by shahriar hasan
Simpler to understand:
更简单的理解:
let primaryArray = [{key:'value'},{},{},{}]
let removeObsoletesArray = []
primaryArray.forEach( element => {
if(element.length > 0){
removeObsoletesArray.push(element)
}
})
回答by StackSlave
Here's what I would do, for progressive enhancement reasons:
这是我会做的,出于渐进增强的原因:
var aryAry = [[{prop: 'value'},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}]];
var a = aryAry[0], r = [];
for(var i=0,l=a.length; i<l; i++){
var n = 0, o = a[i];
for(var q in o){
n++;
}
if(n > 0){
r.push(o);
}
}
console.log(r);
回答by Rajesh Bose
let arr = [{a:1},{},{c:3}];
arr = _.filter(arr,v => _.keys(v).length !== 0);
console.log(arr)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
arr= _.filter(arr,v => _.keys(v).length !== 0);
arr= _.filter(arr,v => _.keys(v).length !== 0);