通过动态变量访问Json值

时间:2013-06-08 02:09:59

标签: 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子句警告测试值总是返回undefined

真心感谢任何帮助

3 个答案:

答案 0 :(得分:2)

您正在跳过image_file_1,直接从image_file转到image_file_2

尝试将imageIndex设置为0,并将0映射到image_file

imageIndex = 0;
continueLoop = true;
while(continueLoop) {
  if(imageIndex == 0) {
    images.push(data[i].image_file);
  }
  // rest of your code unchanged

答案 1 :(得分:2)

据我了解您的代码,您将获得所有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"]

答案 2 :(得分:0)

在这种情况下,最好的选择是使image_files成为JSON中的数组。

[{
   ...
  }, {
    "type": "button",
    "name": "Off2",
    "tabname": "3",
    "image_files": ["path\\Off2.gif", "path\\On2.gif","path\\half.gif"]
  }
]

然后你可以优雅地迭代那些。

但是既然我们都知道必须与其他人的JSON合作的痛苦,我提取这些数据的方式如下:

images = []
$.each(data, function(i, item) {
    imageIndex = 0
    while ( true ) {
        image = item["image_file" + ( imageIndex === 0 ? "" : "_" + imageIndex )]
        if ( typeof image === 'undefined' ) {
            break
        }
        images.push(image)
        imageIndex += 1
    }
})
相关问题