JSON Loop数组,它是一个对象的值

时间:2018-09-02 15:55:25

标签: javascript jquery json

我有一个带有一堆值的JavaScript对象{},其中一个值是数组[]。转换为JSON后,将如下所示。

{
  "header-name": "",
  "header-role": "",
  "header-phone": "",
  "header-website": "",
  "header-email": "",
  "header-location": "",
  "exp-one": "ssfsdf",
  "exp-two": "sdfsdf",
  "exp-three": "",
  "exp-four": "",
  "exp-five": "",
  "exp-six": "",
  "exp-sub": [
    "1",
    "2",
    "3",
    "4",
    "5"
  ]
}

我可以使用var result = $.parseJSON(data); $.each(result, function(k, v) {});

遍历JSON

我想做的是也遍历位于对象"exp-sub"中的那个数组,类似。

$.each(result, function(k, v) {
    if (v == "exp-sub"){
        $.each(k, function(key, val) {
            //loop over array, this doesn't work though
        }
    }
});

也尝试过for循环,但也不起作用,谢谢您的帮助。

1 个答案:

答案 0 :(得分:1)

实际上k是关键,即 exp-sub ,因此您必须比较k并遍历v

var result={"header-name":"","header-role":"","header-phone":"","header-website":"","header-email":"","header-location":"","exp-one":"ssfsdf","exp-two":"sdfsdf","exp-three":"","exp-four":"","exp-five":"","exp-six":"","exp-sub":["1","2","3","4","5"]}

$.each(result, function(k, v) {
    //console.log(k, v)
    if (k == "exp-sub"){
      $.each(v, function(index, val) {
       console.log(val)
}); 
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>