Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter null from array of objects?

I wanted to ask how to filter my array. In this case my array fills with null object and no null object

[null,{"position":{"lat":50.8999208,"lng":20.6258},"vin":22222}]

normally if null doesn't appear the array looks like this:

`[{"position":{"lat":22.8999208,"lng":22.6258},"vin":11111},{"position":{"lat":50.8999208,"lng":20.6258},"vin":22222}]`

But in this case in my programming scenario the first object is nulled and I have to filter this array or maybe copy no-null objects from this array to another array and then compute or error will occur. How should I do it?

Best regards!

like image 458
Snooze Snoze Avatar asked Dec 28 '25 22:12

Snooze Snoze


2 Answers

You could filter the array by checking the data.

var array = [null, { position: { lat: 50.8999208, lng: 20.6258 }, vin: 22222 }],
    withoutNull = array.filter(v => v !== null);

console.log(withoutNull);
like image 170
Nina Scholz Avatar answered Dec 31 '25 12:12

Nina Scholz


Or just check truthy values:

truthyValues = array.filter(v => v);

let array = [null,{"position":{"lat":50.8999208,"lng":20.6258},"vin":22222}],
    truthyValues = array.filter(v => v);

console.log(truthyValues);
like image 34
StepUp Avatar answered Dec 31 '25 11:12

StepUp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!