2

I am working with Leaflet for a map on my site. I want to build the layer switcher dynamically. The constructor takes an object, with key being name of the layer to display on map and value being the layer object itself. I am building the switcher dynamically from an array returned by AJAX. The problem I'm having is that I don't know how to get the value of an array object to be the key in my new object. My code looks like this:

$.ajax ({
    url: '...',
    data: { ... },
    dataType: 'json',
    success: function (data) {
        var overlayMaps = {};
        for (var i in data.elems) {
            var layer = new Layer (...);
            overlayMaps = $.extend ({}, overlayMaps, {data.elems[i].name : layer});
            map.addLayer (layer);
        }
        map.addControl (new L.Control.Layers (baseMaps, overlayMaps));
    }
});

My question is how to do line #9. data.elems[i].name doesn't want to work. I get this error missing : after property id, pointing right to the . after data. Any ideas?

4
  • 1
    What do you mean when you say it doesn't 'want to work'? Does that mean that is doesn't have a value or what? What do you see if you add data.elems[i] to your watch list in the debugger? Commented Apr 9, 2012 at 18:41
  • Object keys can only be strings. If you pass anything other than a string, it will be coerced to a string. Commented Apr 9, 2012 at 18:42
  • I mean I get this error missing : after property id, pointing right to the . after data. Sorry for not including that. Commented Apr 9, 2012 at 18:43
  • And that's my problem. How do I get the value to be a string? Commented Apr 9, 2012 at 18:43

1 Answer 1

3

I think you're just looking for bracket notation. Instead of this:

overlayMaps = $.extend ({}, overlayMaps, {data.elems[i].name, layer});

you want this:

var opts = {};
opts[data.elems[i].name] = layer;
overlayMaps = $.extend ({}, overlayMaps, opts);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.