admin管理员组文章数量:1295901
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?
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?
Share Improve this question edited Apr 19, 2019 at 17:03 adiga 35.3k9 gold badges65 silver badges87 bronze badges asked Mar 26, 2019 at 15:04 Anilkumar iOS DeveloperAnilkumar iOS Developer 3,75510 gold badges61 silver badges119 bronze badges 1- How do I test for an empty JavaScript object? - In this thread you will get full brief about how to check empty object. – Adnan Sharif Commented Mar 26, 2019 at 15:22
3 Answers
Reset to default 11You 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)
本文标签: How to delete empty objects from an Array in javascriptStack Overflow
版权声明:本文标题:How to delete empty objects from an Array in javascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741619882a2388746.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论