【问题标题】:how to iterate this kind of json?如何迭代这种json?
【发布时间】:2014-11-30 16:47:47
【问题描述】:
[
    {
        "id": 1,
        "name": "John",
        "age": 11
    },
    {
        "id": 2,
        "name": "Maria",
        "age": 12
    },
    [
        {
            "id": 1,
            "store": "market place",
            "phone": 1234567890,
            "type": "market"
        },
        {
            "id": 2,
            "store": "ration",
            "phone": 1234567890,
            "type": "animal"
        }
    ]
]

我正在尝试获取 storephonetype 值。但我只得到了nameage

我有这个:

$.each(data, function (i, x) {
     alert(x.phone) // give all null 4x times
});

如何迭代我的所有 json?我试图添加另一个each,但它显示给我undefined

【问题讨论】:

标签: jquery


【解决方案1】:

那是非常奇怪的数据结构。问题在于你有两种类型,对象和数组末尾的另一个数组。 因此,要获取 store 和 phone 值,您需要识别此数组中的数组:

$.each(data, function(i, x) {
    //Test if item is array
    if ($.isArray(x)) {
        //If it is, cycle throught it, find desired data
        $.each(x, function(i2, x2) {
            alert(x2.phone)
            alert(x2.store)
        });
    }
});

【讨论】:

  • 我知道这对我来说很奇怪和错误,但在我想出另一种我正在尝试做的事情之前,这是必要的。
猜你喜欢
  • 2011-04-16
  • 1970-01-01
  • 1970-01-01
  • 2019-06-13
  • 1970-01-01
  • 2012-12-18
  • 2012-06-22
  • 2018-09-12
  • 1970-01-01
相关资源
最近更新 更多