JSON对象数组

10

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

我希望实现的目标是获得一个对象数组。这些对象看起来像这样:

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

我希望创建一个餐厅对象的数组,并使用一些逻辑填充距离字段,然后根据距离字段对数组进行排序。
我可以创建一个JSON对象数组吗?还是有其他使用JSON实现此目标的方法?
非常感谢您的帮助。

是的,您可以创建一个对象数组。 - Shef
从技术上讲,2D数组是有效的JSON(http://json.org/)。实际上,几乎任何没有特殊功能的对象(即DOM对象和诸如“new Date()”和“new Image()”之类的对象)都可以作为JSON。但是,使用具有命名值的对象绝对是更好的方法。 - namuol
4个回答

10
// 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; });

8

首先,这根本不是 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));

7
当然可以。它看起来会像这样:
{ "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" 的外层字段名并不是必要的,当然如果你在传输数据时包含了其他信息,该字段名可能会有所帮助。

请问您能告诉我如何做吗? - user6856823

3
[
    { "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”字段并根据该值进行排序。 - namuol

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接