【问题标题】:how to loop same key to get different associated value in json/object如何循环相同的键以在 json/object 中获取不同的关联值
【发布时间】:2016-10-17 12:11:19
【问题描述】:

我有这样的 json/object

{city: "bangalore", other:"other data", pic: "bangalore.jpg",city: "delhi", pic: "delhi.jpg"}

我有 2 个城市及其图片。我想将它们附加到单独的 2 div 中。

这里我只是想遍历每个城市?但失败了我该怎么做?

$.ajax({
      url: "mul.php",
      type: "POST",
      data: {
        a: a
      },
      dataType: "text",
      success: function(data) {
        var obj = $.parseJSON(data);
        console.log(obj.city); // i'm getting only delhi , what about bangalore?
        $.each(obj.city, function(i, city) {
          console.log(city); // i'm getting error
        })
      }
});

【问题讨论】:

  • 在单个对象中,多个键不能具有相同的名称。像这样创建对象数组[ { "city": "bangalore", "other": "other data", "pic": "bangalore.jpg" }, { "city": "delhi", "pic": "delhi.jpg" } ]
  • 好的,在那种情况下我如何循环它们
  • 你可以知道哪个城市映射到哪个图片。您需要有一系列城市来为每个城市做一个

标签: jquery json object


【解决方案1】:

像这样创建一个对象数组。

对象键不能重复。

[
    {
        "city": "bangalore",
        "other": "other data",
        "pic": "bangalore.jpg"
    },
    {
        "city": "delhi",
        "pic": "delhi.jpg"
    }
]

【讨论】:

    【解决方案2】:

    正如其他人所说,您需要将每个城市放在一个数组中的单独对象中。对象键不能复制,即使这在某种程度上是合法的,你怎么知道哪张图片与哪个城市相关联?将城市及其图片分成单独的对象后,您可以通过访问数组中每个对象的city 属性来遍历它们。请注意,传递给$.each() 的第一个参数是数组或对象本身,不是您要显示的属性:

    var arr = [
        {
            "city": "bangalore",
            "other": "other data",
            "pic": "bangalore.jpg"
        },
        {
            "city": "delhi",
            "pic": "delhi.jpg"
        }
    ];
    
    $.each(arr, function(i, obj) {
      console.log(obj.city);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-10
      • 2019-05-11
      相关资源
      最近更新 更多