6

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?

  • with forEach function? – John Powell Nov 12 '15 at 9:16
6

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.