当前位置: 代码迷 >> JavaScript >> Javascript-在多维数组中查找多个值
  详细解决方案

Javascript-在多维数组中查找多个值

热度:310   发布时间:2023-06-08 09:36:29.0

有一些JSON,我需要通过获取一些标识。 JSON如下所示:

var carousel = [
  {
    "acf": {
      "content": [
        {
          "acf_fc_layout": "custom",
          "content": "Some text"
        },
        {
          "acf_fc_layout": "exhibition",
          "exhibition": 2594
        },
        {
          "acf_fc_layout": "exhibition",
          "exhibition": 1234
        }
      ]
    },
  }
]

对于acf_fc_layout == exhibition每个content ,我必须获取acf_fc_layout == exhibition的值(ID),以便可以将其用于获取其他数据。 正如你可以看到有多个展览的ID以及。

在这里,我的困惑是,有两个对象和数组,以及嵌套的时候。 我已经做了jQuery的一些类似的东西,但这不在这个时间的问题。 不要以为我需要IE8的支持,但仍觉得这个棘手..

carousel[0].acf.content.forEach(function (item) {
  if (item["acf_fc_layout"] === "exhibition") {
    // do some stuff
    // id for exhibition placed in item["exhibition"] 
  }
});

如果您的JSON看起来像您所说的那样,那么这是一个简单的解决方案:

var i;
for (i = 0; i < carousel[0].acf.content.length; i++) {
    if (carousel[0].acf.content[i].acf_fc_layout === "exhibition") {
        // do something with carousel[0].acf.content[i].exhibition
    }
}

另外,如果您的JSON中包含更多内容,则可能与此有关:

var i, j;
for (i = 0; i < carousel.length; i++) {
    if (typeof carousel[i].acf != 'undefined' && typeof carousel[i].acf.content != 'undefined') {
        for (j = 0; j < carousel[i].acf.content.length; j++) {
            if (carousel[i].acf.content[j].acf_fc_layout === "exhibition") {
                // do something with carousel[i].acf.content[j].exhibition
            }
        }
    }
}

$(carousel).each(function(i, el){

    $(el.acf.content).each(function(i, el){
        if(el.acf_fc_layout === 'exhibition') {
            $('<div>', {
                text: el.exhibition
            }).appendTo($('#results'));
        }
    });

});

如果acf有很多content ,则需要运行附加循环,并且acf必须是对象数组。

使用当前结构,您需要使用foreach并检查该值。

 var carousel = [
  {
    "acf": {
      "content": [
        {
          "acf_fc_layout": "custom",
          "content": "Some text"
        },
        {
          "acf_fc_layout": "exhibition",
          "exhibition": 2594
        },
        {
          "acf_fc_layout": "exhibition",
          "exhibition": 1234
        }
      ]
    },
  }
];

$.each(carousel[0].acf.content,function (i,v){
    if(v.acf_fc_layout == "exhibition")
        $(".result").append(v.exhibition+"<br>");
    });

  相关解决方案