Tuesday, May 14, 2024
 Popular · Latest · Hot · Upcoming
149
rated 0 times [  153] [ 4]  / answers: 1 / hits: 8349  / 2 Years ago, sat, august 6, 2022, 12:00:00

I have a global list of mountains. I want to filter all French mountains. To do this, I need to check if iso3166_1Alpha2 is set to FR. The problem is that not all mountains have a value. The script dies after it hits a null value I think because this is the error:


Uncaught (in promise) TypeError: Cannot read properties of null (reading 'iso3166_1Alpha2')

This is my script. Seems my check of !== null is not working and do not know why.


function addJSON() {
let url = "https://development.example.com/admin/mtn/json/mtn_areas.geojson";
fetch(url)
.then(function (response) {
return response.json();
})
.then(function (data) {
let mtn = data.features;
for (var i = 0; i < mtn.length; i++) {
if (mtn[i].properties.location.iso3166_1Alpha2 !== null) {
x = mtn[i].properties.location.iso3166_1Alpha2;
console.log(x);
}
}
});
}

More From » json

 Answers
6

It seems like your are getting an item which doesn't have a location property, in which case your condition won't help preventing it. Try changin your function as below. Notice I'm using Optional chaining, the ?. syntax, to avoid any null or undifined property.


function addJSON() {
let url = "https://development.example.com/admin/mtn/json/mtn_areas.geojson";
fetch(url)
.then(function (response) {
return response.json();
})
.then(function (data) {
let mtn = data.features;
for (var i = 0; i < mtn.length; i++) {
if (mtn[i]?.properties?.location?.iso3166_1Alpha2) {
x = mtn[i].properties.location.iso3166_1Alpha2;
console.log(x);
}
}
});
}

[#44] Friday, July 8, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
shantelc

Total Points: 737
Total Questions: 120
Total Answers: 104

Location: Nicaragua
Member since Tue, Dec 8, 2020
4 Years ago
shantelc questions
;