javascript - 通过动态变量访问 Json 值

标签 javascript json variables dynamic

好的,首先是 json 结构

[{
    "type": "button",
    "name": "Off",
    "tabname": "1",
    "image_file": "path\\Off.gif"
  }, {
    "type": "button",
    "name": "Off1",
    "tabname": "2",
    "image_file": "path\\Off1.gif",
    "image_file_1": "path\\On1.gif"
  }, {
    "type": "button",
    "name": "Off2",
    "tabname": "3",
    "image_file": "path\\Off2.gif",
    "image_file_1": "path\\On2.gif",
    "image_file_2": "path\\half.gif"
  }
]

image_file 字段可以有多个条目(即 image_file、image_file_1、image_file_2 等),我如何在循环中动态访问它?

当前不工作的代码(只是相关的东西)

$.each(data, function (i, item) {
  var images = [];
  imageIndex = 1;
  continueLoop = true;
  while(continueLoop) {
    if(imageIndex == 1) {
      images.push(data[i].image_file);
    }
    else {
      var testVal = 'image_file_' + imageIndex;
      alert(data[i][testVal]);
      if(data[i][testVal] === undefined) {
        continueLoop = false;
      }
      else {
        images.push(data[i][testVal]);

      }
    }
    imageIndex++;
  }
});

第一次迭代工作正常(即 if (imageIndex == 1) 位),但是我放入的 else 子句警报总是测试值返回未定义

任何帮助将不胜感激

最佳答案

据我了解您的代码,您将获得所有 image_file 属性,甚至是带有数字的属性。 You can easily do it with this :

var images = [];

//iterate through the array
$.each(data, function (i, item) {

  //iterate through each property
  $.each(item, function (key, value) {

    //if the property starts with image_file, push into the array
    if (key.indexOf('image_file') === 0) images.push(value);
  });
});

console.log(images); // ["path\\Off.gif","path\\Off1.gif","path\\On1.gif","path\\Off2.gif","path\\On2.gif","path\\half.gif"]

关于javascript - 通过动态变量访问 Json 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16995333/

相关文章:

javascript - React 前端 + Express.js Sessions

Javascript/Html 显示全部/隐藏所有内容

java - 如何使用 gson 将对象序列化为一个元素的列表

java - 使用 editcell 启用卡住 jqgrid

php - 从 PHP 类引用 SQL 结果

variables - 在 angularjs 的 src 属性中使用 ng-repeat 变量?

linux - 在 Bash 中添加/平均多个变量

javascript - 如何使用 Canvas 将 div 渲染的 .png 逆时针旋转 90°?

javascript - 通过多选显示/隐藏多个 Div

javascript - 根据数组值 angularjs 分配 ng-class 值