2015-10-30 37 views
0

我想將多個對象添加到一個關鍵的JavaScript 所需的輸出:添加多個對象在一個關鍵

{1:[{city_name:'XYZ',city_id:21},{city_name:'ABC',city_id:2}]} 

代碼片段:

for(var key = 1; key <= largest ; key++) 
{ 

    for(var i =0; i<subservices.length ; i++) 
    {        
     if(key == subservices[i].from_city_order) 
     {       
      if(!(key in childMap)) {          
       childMap[key] =(cityIdMap[subservices[i].to_city_id]);  
      } else if(key in childMap){         
       //same key value should have multiple objects in the array  
      }                 
     }                  
    } 
}                   
+0

請加上'subservices','cityIdMap'和'childMap'更多信息。 –

+0

1.subservices是一個即將獲取城市id的對象數組。 – user2452537

+0

不,不。我的意思是,以JSON格式顯示其內容。 –

回答

0

當然,你不能有多個對象爲同一把鑰匙。這就是關鍵價值關係的重點。你能擁有的是地圖,其值是數組,那麼你的地圖可能是這樣的:

cityZipCodesMap = { 
    'London' => [111,222,333], 
    'NY' => [444], 
    'LA' => [555,666] 
} 

// With this you can do something like this: 

if(!(cityName in cityZipCodesMap)){ 
    cityZipCodesMap[cityName] = []; 
}else{ 
    cityZipCodesMap[cityName].push(newZipCode); 
} 
相關問題