简体   繁体   中英

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 :

 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.

 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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