我正在尝试将信息“推送”到json对象。
我有这个json对象:
var lol = {
"locations": {
"United States": [
{
"Illinois": [
{
"Chicago": "http://website1.com/",
"Springfield": "http://website2.com/"
}
],
"New York": [
{
"New York": "http://website3.com/",
"Brooklyn": "http://website4.com/"
}
]
}
]
}
};
我正在尝试做一些事情:
答案 0 :(得分:3)
首先让我们整理你的对象。你的括号太多了。
var lol = {
"locations": {
"United States": {
"Illinois": {
"Chicago": "http://website1.com/",
"Springfield": "http://website2.com/"
},
"New York": {
"New York": "http://website3.com/",
"Brooklyn": "http://website4.com/"
}
}
}
};
现在已经完成,添加新城市很简单:
lol.locations["United States"]["New York"]["Queens"] = "http://website5.com/";
检查状态是否存在:
if( lol.locations["United States"]["Illinois"]) {
// it exists! Do something!
}
对城市进行排序有点困难。对象是不可移植的,密钥由浏览器处理。也就是说,您可以使用数组“helper”:
var cities = Object.keys(lol.locations["United States"]["New York"]);
cities.forEach(function(city) {
console.log(city+": "+lol.loctions["United States"]["New York"][city]);
});
希望这有帮助!