简体   繁体   English

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

[英]How to delete empty objects from an Array in javascript?

I am getting array like below.我得到如下数组。

[{},
 {},
 {},
{ label: '2015', showLabels: '1,' },
 {},
 {},
 {},
{ label: ‘2017’, showLabels: '1,' }]

but, I would like to delete empty indexes.但是,我想删除空索引。

I have tried following to delete.我试过以下删除。 But, Not working as expected.但是,没有按预期工作。

const filteredFinalYearArr = yearArray.filter(function (el) {
  return el != null;
});

Note: This is dynamic data注意:这是动态数据

Any suggestions?有什么建议么?

You could filter all the objects which have non-zero number of keys :您可以filter所有具有非零keys数的对象:

 let yearArray = [{},{},{},{label:'2015',showLabels:'1,'},{},{},{},{label:'2017',showLabels:'1,'}] let filtered = yearArray.filter(el => Object.keys(el).length) console.log(filtered)

See this article about best ways to check if an Object is empty.请参阅这篇关于检查对象是否为空的最佳方法的文章

 const years = [ {}, {}, {}, { label: '2015', showLabels: '1,' }, {}, {}, {}, { label: '2017', showLabels: '1,' } ] const hasValues = obj => { for(var key in obj) { if(obj.hasOwnProperty(key)) return true } return false } const filteredYears = years.filter(y => hasValues(y)) console.log(filteredYears)

Another way is to use reduce to build the array.另一种方法是使用reduce来构建数组。

 const yearArray = [{},{},{},{label:'2015',showLabels:'1,'},{},{},{},{label:'2017',showLabels:'1,'}] const filteredFinalYearArr = yearArray.reduce((o, i) => {Object.keys(i).length > 0 && o.push(i); return o}, []) console.log(filteredFinalYearArr)

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

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