2017-09-19 13 views
1

別の変数にマッチングすることでアクセスしたいキー値のペアが ``私は割り当てられています。例えばjavascriptのキー値ペアへの変数のマッピング

var dict = []; 

dict.push({ 
    key: "shelter", 
    value: "icon1" 
}); 

dict.push({ 
    key: "legal", 
    value: "icon2" 
}); 


dict.push({ 
    key: "bar", 
    value: "icon3" 
}); 

私は、以下の機能のコレクションを持っていた場合、私はsymbolがコンソールにログインするdict.value、その後dict.keyにマッチしたいと思います。したがって、この場合には、ログは次のようになり"icon1", "icon2", "icon3"

var places = { 
    "type": "FeatureCollection", 
    "features": [{ 
     "type": "Feature", 
     "properties": { 
      "icon": "shelter" 
     }, 
     "geometry": { 
      "type": "Point", 
      "coordinates": [-77.038659, 38.931567] 
     } 
    }, { 
     "type": "Feature", 
     "properties": { 
      "icon": "legal" 
     }, 
     "geometry": { 
      "type": "Point", 
      "coordinates": [-77.003168, 38.894651] 
     } 
    }, { 
     "type": "Feature", 
     "properties": { 
      "icon": "bar" 
     }, 
     "geometry": { 
      "type": "Point", 
      "coordinates": [-77.090372, 38.881189] 
     } 

    }] 
}; 


places.features.forEach(function(feature) { 
    var symbol = feature.properties['icon']; 

console.log(dict.value) 

}); 

どのようにしてこれをJavaScriptで書くでしょうでしょうか?

+1

'[]' – Redu

+1

あなたの辞書には基本的に[地図]であるため 'dict'は、選択するための良い名前ではありません(https://developer.mozilla.org/en- US/docs/Web/JavaScript/Reference/Global_Objects/Map)。 'dict.get(symbol)'を使うか、その配列を単純なオブジェクトに置き換えて 'dict [symbol]'を実行してください。 – T4rk1n

+0

なぜあなたはあなたのキー、 'key'と' value'を呼びますか?記述されているとおりにそれらを使用してみませんか(たとえば、{シェルター: 'アイコン'、法的: 'アイコン2'、...} ')? – BotNet

答えて

1

オブジェクトを希望のキー値ペアの辞書として使用できます。次に、反復の値を辞書のキーとします。

var dict = { shelter: "icon1", legal: "icon2", bar: "icon3" }, 
 
    places = { type: "FeatureCollection", features: [{ type: "Feature", properties: { icon: "shelter" }, geometry: { type: "Point", coordinates: [-77.038659, 38.931567] } }, { type: "Feature", properties: { icon: "legal" }, geometry: { type: "Point", coordinates: [-77.003168, 38.894651] } }, { type: "Feature", properties: { icon: "bar" }, geometry: { type: "Point", coordinates: [-77.090372, 38.881189] } }] }; 
 

 
places.features.forEach(function (feature) { 
 
    var symbol = feature.properties.icon; 
 
    console.log(dict[symbol]); 
 
});

関連する問題