简体   繁体   English

如何从JS中的数组中删除空对象

[英]How can I remove empty object in from an array in JS

I have an array of objects and when I stringify, it looks like this:我有一个对象数组,当我进行字符串化时,它看起来像这样:

"[[{"entrReqInv": "Neither"},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}]]"

How can I remove the empty {} s?如何删除空的{}

var newArray = array.filter(value => Object.keys(value).length !== 0);

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

I would recommend using the following code:我建议使用以下代码:

var newArray = array.filter(value => JSON.stringify(value) !== '{}');

I did not use Object.keys(value).length !== 0 because it not only removes empty objects { } but also removes empty arrays [ ] .我没有使用Object.keys(value).length !== 0因为它不仅删除空对象{ }还删除空数组[ ] If you only want to remove empty objects, use the above method.如果您只想删除空对象,请使用上述方法。

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

Simpler to understand:更简单的理解:

let primaryArray = [{key:'value'},{},{},{}]
let removeObsoletesArray = []
primaryArray.forEach( element => {
   if(element.length > 0){
      removeObsoletesArray.push(element)
   }
})

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);
const arrValues = [{ x: 100 }, { x: 200 }, {}]; let filteredArra = arrValues.filter( obj => !(obj && Object.keys(obj).length === 0) );

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

if your data structures like this: [ {} , {} ];如果你的数据结构是这样的:[ {} , {} ]; then you can simply use this smooth code.那么你可以简单地使用这个流畅的代码。

array.filter(x=> !jQuery.isEmptyObject(x))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM