[GIS] How to iterate through the attributes of a feature in Leaflet

esri-leafletjavascriptleaflet

I receive polygons via the ESRI REST API with Leaflet. I want to iterate through all attributes of a feature in order to create a custom pop-up for it.

My code looks like this:

myLayer.on('click', function (evt) 
{
   feature = evt.layer.feature;
   //Here I want to iterate ...
}

I know that I can access the attributes like this:

feature.properties.myAttribute

But how can I iterate through all attributes?

Best Answer

If my understanding is correct, you want to read all properties of the given event layer, without knowing in advance which properties are set and available?

In that case, this is a simple JavaScript problem, for which you can use Object.keys(feature.properties) to get the array of available "attributes" in feature.properties. Then simply iterate over that array:

myLayer.on('click', function (evt) {
    var feature = evt.layer.feature,
        props = feature.properties,
        attrs = Object.keys(props),
        attribute, value;

    for (var i = 0; i < attrs.length; i += 1) {
        attribute = attrs[i];
        value = props[attribute];
        // use the value to do something...
    }
});

You could also use the for...in:

for (attribute in props) {
    value = props[attribute];
}