創建關聯多維數組對象我有一個數據庫表3列:如何在JavaScript
id | city | area |
--------------------------------------
2000 | Paris | City center |
2010 | Barcelona | Las Ramblas |
2030 | Madrid | City center |
2400 | Paris | City center |
3600 | Barcelona | City center |
3670 | Madrid | City center |
5000 | Paris | Eiffel tower |
7000 | Paris | Eiffel tower |
1000 | Barcelona | Las Ramblas |
2500 | Madrid | city center |
值在id
柱是獨一無二的!
據我試圖在屬於下城區得到每個區域的表:
$scope.cities = [
{
name: "city_1",
areas: [
{name: "area_1"},
{name: "area_2"}
]
},
{
name: "city_2",
areas: [
{name: "area_1"},
{name: "area_2"},
{name: "area_3"}
]
},
{
name: "city_3",
areas: [
{name: "area_1"}
]
}
];
我已經要求添加JSON輸出,在這兒呢。
[{
"id": "2000",
"city": "Paris",
"cityArea": "City center"
}, {
"id": "2010",
"city": "Barcelona",
"cityArea": "Las Ramblas"
}, {
"id": "2030",
"city": "Madrid",
"cityArea": "City center"
}, {
"id": "2400",
"city": "Paris",
"cityArea": "City center"
}, {
"id": "3600",
"city": "Barcelona",
"cityArea": "City center"
}, {
"id": "3670",
"city": "Madrid",
"cityArea": "City center"
}, {
"id": "5000",
"city": "Paris",
"cityArea": "Eiffel tower"
}, {
"id": "7000",
"city": "Paris",
"cityArea": "Eiffel tower"
}, {
"id": "1000",
"city": "Barcelona",
"cityArea": "Las Ramblas"
}, {
"id": "2500",
"city": "Madrid",
"cityArea": "city center"
}]
我已經嘗試過:
var duplicatedCities = [];
for(var i=0; i<$scope.results.length; i++) {
duplicatedCities.push($scope.results[i].city);
}
//output
// ["Paris","Barcelona","Madrid","Paris","Barcelona","Madrid","Paris","Paris","Barcelona","Madrid"];
var uniqueCities = [];
uniqueCities.push(duplicatedCities.filter(function(elem, index, self) {
return index == self.indexOf(elem);
}));
//output
//["Paris","Barcelona","Madrid"];
,但現在什麼?
[創建與多維數組的多維對象(http://stackoverflow.com/questions/11648586/create-multidimensional-object-with-multidimentional-arrays) – Tibrogargan
聲音的可能的複製像一個挑戰。你有嘗試過什麼嗎?你如何從數據庫表中獲取數據到JavaScript? –
你得到一個json字符串,並且想要按照描述創建'$ scope.cities'。對?然後提供該json。 –