我想在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 :(得分: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);
}