I am practising with vainilla JS, fetching some data from a public API, and manipulating the DOM with them.
I am finding a problem i am not sure how to solve. The object has some null values in some fields , but other times that field contain some information. When I run a loop over it, it always breaks when it reaches one field with a null value.
I would like to know what the best approach should be.
One might be to "clean" the null values from the object, and store the "new cleaned" object in a variable . But guess that´s not the way to go if the API were big.
My second idea would be to include an if condition in the loop, saying to jump to the next one, if the value found is === null , something like this :
function createSomeCards(myObject) {
for (let i=0; i < myObject.lenght; i++) {
if (value === null) { i = i+1 } else { i = i }
here would go the rest of the code to build the cards
i don`t know if that is the approach (even if my code is waz wrong), or should be different. The object has an structure similar to this :
myObject = [
{
"Habitat Impacts": "Area closures ",
"Image Gallery": [
{
"src": "anImage.jpg",
"alt": "some text",
"title": "more text"
},
{
"src": null,
"alt": "additional text",
"title": "a title here"
},
{
"src": "otherImg.jpg",
"alt": "imgInfor",
"title": null
}
],
"Management": null,
"Scientific Name": "Urophycis tenuis",
"Species Illustration Photo": {
"src": null,
"alt": "Illustration",
"title": ""
},
"Ecosystem Services": null,
"Servings": "1",
"last_update": "05/19/2021 - 13:04"
}]
I update the comment with the JS code in which I am finding the issue with the Null values
function createCards(myObject) {
let cardContainer = document.getElementById('cardContainer');
for (let i = 0; i < myObject.length; i++) {
aInfoButtonLeft.onclick = function () {
let divSlidAct = document.getElementById('sliderImg')
let imgSlidAct= document.createElement('img');
imgSlidAct.setAttribute('src', myObject[i]['Image Gallery'][i]['src']);
imgSlidAct.append(divSliderActive);
}
}
}