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?
adiga
35.4k9 gold badges66 silver badges88 bronze badges
asked Mar 26, 2019 at 15:04
Anilkumar iOS Developer
3,81510 gold badges63 silver badges121 bronze badges
-
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– Adnan Sharif2019年03月26日 15:22:42 +00:00Commented Mar 26, 2019 at 15:22
3 Answers 3
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)
answered Mar 26, 2019 at 15:06
adiga
35.4k9 gold badges66 silver badges88 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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)
answered Mar 26, 2019 at 15:10
Francis Leigh
2,01014 silver badges28 bronze badges
2 Comments
adiga
"Object.keys(obj).length is not supported on Firefox < 4 and IE < 9" Neither are arrow functions. OP is using react native. So, they will have traspilers or polyfills to support old browsers :)
Francis Leigh
@adiga oh yeah. thanks for pointing out. serves me right eh? :-D
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)
answered Mar 26, 2019 at 15:18
Get Off My Lawn
36.6k47 gold badges201 silver badges381 bronze badges
Comments
lang-js