【问题标题】:Array of JSON ObjectsJSON 对象数组
【发布时间】:2011-10-11 02:41:35
【问题描述】:

我正在尝试使用 JSON 而不是一些二维数组来重新实现页面。

我希望完成的是获得一组对象。对象看起来像这样:

{ // Restaurant
  "location" : "123 Road Dr",
  "city_state" : "MyCity ST",
  "phone" : "555-555-5555",
  "distance" : "0"
}

我想创建一个包含这些餐厅对象的数组并使用一些逻辑填充距离字段,然后根据距离字段对数组进行排序。

我可以创建一个 JSON 对象数组,还是有其他的 JSON 对象可以实现这个目标?

非常感谢您的帮助。

【问题讨论】:

  • 是的,你可以创建一个对象数组。
  • 从技术上讲,二维数组 valid JSON。事实上,几乎任何不具备特殊能力的对象(即 DOM 对象和诸如 new Date()new Image() 之类的东西)都可以作为 JSON。但是您肯定会通过使用具有命名值的对象来采取更好的方法。

标签: javascript json object


【解决方案1】:

当然可以。它看起来像这样:

{ "restaurants": [ 
    { "location" : "123 Road Dr", "city_state" : "MyCity ST", "phone" : "555-555-5555", "distance" : "0" } , 
    { "location" : "456 Fake St", "city_state" : "MyCity ST", "phone" : "555-123-1212", "distance" : "0" } 
] }

“restaurants”的外部字段名称当然不是必需的,但如果您在传输的数据中包含其他信息,它可能会有所帮助。

【讨论】:

  • 你能告诉我怎么做吗?
【解决方案2】:
[
    { "location" : "123 Road Dr", "city_state" : "MyCity ST", "phone" : "555-555-5555", "distance" : "0" },
    { "location" : "123 Road Dr", "city_state" : "MyCity ST", "phone" : "555-555-5555", "distance" : "0" },
    { "location" : "123 Road Dr", "city_state" : "MyCity ST", "phone" : "555-555-5555", "distance" : "0" }
]

【讨论】:

  • 最初的问题是询问如何操作distance 字段,然后按该值排序。
【解决方案3】:
// You can declare restaurants as an array of restaurant objects
restaurants = 
[
    {
        "location" : "123 Road Dr", 
        "city_state" : "MyCity ST", 
        "phone" : "555-555-5555", 
        "distance" : "1" 
    },
    {
        "location" : "456 Avenue Crt", 
        "city_state" : "MyTown AL", 
        "phone" : "555-867-5309", 
        "distance" : "0" 
    }
];

// Then operate on them with a for loop as such
for (var i = 0; i< restaurants.length; i++) {
    restaurants[i].distance = restaurants[i].distance; // Or some other logic.
}

// Finally you can sort them using an anonymous function like this
restaurants.sort(function(a,b) { return a.distance - b.distance; });

【讨论】:

    【解决方案4】:

    首先,这根本不是 JSON,您只是在使用 Javascript 对象。 JSON 是一种表示对象的文本格式,没有“JSON 对象”之类的东西。

    你可以像这样为你的对象创建一个构造函数:

    function Restaurant(location, city_state, phone, distance) {
      this.location = location;
      this.city_state = city_state;
      this.phone = phone;
      // here you can add some logic for the distance field, if you like:
      this.distance = distance;
    }
    
    // create an array restaurants
    var restaurants = [];
    // add objects to the array
    restaurants.push(new Restaurant("123 Road Dr", "MyCity ST", "555-555-5555", 0));
    restaurants.push(new Restaurant("123 Road Dr", "MyCity ST", "555-555-5555", 0));
    restaurants.push(new Restaurant("123 Road Dr", "MyCity ST", "555-555-5555", 0));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-31
      • 2019-08-11
      • 2011-01-10
      • 1970-01-01
      • 2018-11-13
      相关资源
      最近更新 更多