Bri*_*eer 4 javascript json object
早上好,
我是JSON的新手,我正在尝试使用JSON而不是某些二维数组重新实现页面.
我希望完成的是获取一系列对象.对象看起来像这样:
{ // Restaurant
"location" : "123 Road Dr",
"city_state" : "MyCity ST",
"phone" : "555-555-5555",
"distance" : "0"
}
Run Code Online (Sandbox Code Playgroud)
我想创建这些餐馆对象的数组,并用一些逻辑填充距离字段,然后根据距离字段对数组进行排序.
我对JSON很新.我可以创建一个JSON对象数组,还是有其他JSON实现这个目标?
非常感谢您的帮助.
凯文
你当然可以。它看起来像这样:
{ "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" }
] }
Run Code Online (Sandbox Code Playgroud)
“restaurants”的外部字段名称当然不是必需的,但如果您在传输的数据中包含其他信息,它可能会有所帮助。
// 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; });
Run Code Online (Sandbox Code Playgroud)
首先,这根本不是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));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
34564 次 |
| 最近记录: |