我有一个键值对,指定为``我想通过匹配一个单独的变量来访问。
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写这个?
答案 0 :(得分: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]);
});