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 = ".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);
}
}
});
}
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./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);
}
}
});
}
Share
Improve this question
edited Aug 6, 2022 at 9:50
Youssouf Oumar
46.6k16 gold badges103 silver badges105 bronze badges
asked Aug 6, 2022 at 9:28
spreadermanspreaderman
1,0862 gold badges14 silver badges50 bronze badges
1 Answer
Reset to default 2It seems like you are getting an item that doesn't have a location
property, in which case your condition won't help prevent it. Try changing your function as below. Notice I'm using Optional chaining, the ?.
syntax, to avoid any null
or undefined
property.
function addJSON() {
let url = "https://development.example./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);
}
}
});
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744207867a4563192.html
评论列表(0条)