首页 > 解决方案 > 如何从 API 中循环遍历数组,其中某些属性的值为 null,而不修改它

问题描述

我正在练习 vainilla JS,从公共 API 获取一些数据,并用它们操作 DOM。

我发现了一个我不知道如何解决的问题。该对象在某些字段中有一些空值,但其他时候该字段包含一些信息。当我在它上面运行一个循环时,它总是在到达一个具有空值的字段时中断。

我想知道最好的方法应该是什么。

一种可能是从对象中“清除”空值,并将“新清除”的对象存储在变量中。但是,如果 API 很大,我想这不是要走的路。

我的第二个想法是在循环中包含一个 if 条件,说如果找到的值是 === null ,则跳转到下一个条件,如下所示:

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

我不知道这是否是方法(即使我的代码是错误的),或者应该不同。该对象具有与此类似的结构:

 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"
    }]

我用 JS 代码更新注释,在其中发现 Null 值存在问题

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);
        }

    }
}

标签: javascriptjson

解决方案


我将把我的原始答案留在这个答案下,因为我认为它仍然相关。

您在数组中有一个数组,并且您没有遍历第二个数组“图片库”。添加第二个循环可以让您获得所有图像。

我添加了一个检查以查看 src 是否为空。这应该会停止您收到的有关 src 为空的任何错误。

function createCards(myObject) {
    let cardContainer = document.getElementById('cardContainer');

    for (let i = 0; i < myObject.length; i++) {

        for (let x=0; x < myObject[i]["Image Gallery"].length; x++) {

                if (myObject[i]['Image Gallery'][x]["src"] === null) {
                    // the source is empty do nothing
                }else{
                    aInfoButtonLeft.onclick = function () {
                    let divSlidAct = document.getElementById('sliderImg')
                    let imgSlidAct= document.createElement('img');
                    imgSlidAct.setAttribute('src', myObject[i]['Image Gallery'][x]["src"]);
                    imgSlidAct.append(divSliderActive);
                }
            }
        }
    }
}

原始答案

你有2 1 个问题。

  1. 您在数组中有一个数组,并且您没有遍历第二个数组“图片库”

2. 'src' 字段是对象的属性,而不是数组的索引。

你有空值的事实并不重要。循环将继续。

请参阅下面的代码和注释。

let 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"
}];

//loop over my object
for (let i=0; i < myObject.length; i++) {

//loop over the image gallery
  for (let x=0; x < myObject[i]["Image Gallery"].length; x++) {
    console.log("src: " + myObject[i]["Image Gallery"][x].src); //notice it .src and not ["src"]
    console.log("alt: " +myObject[i]["Image Gallery"][x].alt);
    console.log("title: " +myObject[i]["Image Gallery"][x].title);
    
    //I commented out this section so the snippet would work 
   /*
    aInfoButtonLeft.onclick = function () {
        let divSlidAct = document.getElementById('sliderImg')
        let imgSlidAct= document.createElement('img');
        imgSlidAct.setAttribute('src', myObject[i]['Image Gallery'][x].src);
        imgSlidAct.append(divSliderActive);
   */
    }

  }


推荐阅读