将变量映射到 javascript 中的键值对

Mapping variables to key value pairs in 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 怎么写?

您可以使用对象作为所需键值对的字典。然后将迭代的值作为字典的键。

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]);
});