1

I want to iterate an array of objects to create one object, the properties of which are named for the current object in the iteration and the values of which use data from the current.

$.each(data, function(idx, obj) {
    baseLayers[idx] = new Array();
    baseLayers[idx][obj.name] = new L.TileLayer(obj.url, {maxZoom: 18, id: obj.key, attribution: mbAttr});
});

at the end, I want to get result an object like this

baseLayers = {
        'Map Box': new L.TileLayer('https://{s}.tiles.mapbox.com/v3/{id}/{z}/{x}/{y}.png', {maxZoom: 18, id: 'examples.map-i875mjb7', attribution: mbAttr}),
        'OSM': new L.TileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {maxZoom: 18, attribution: mbAttr})
};
4
  • What is your current code producing? Commented Feb 28, 2015 at 16:23
  • 'Map Box' and 'OSM' is what I'm getting from obj.name Commented Feb 28, 2015 at 16:23
  • I just noticed, after $.each block when I tried to get length of baseLayer[0] it gives as 0 but, it has key baseLayers[0]['Map Box'] Commented Feb 28, 2015 at 16:25
  • JSON is a string. There is no JSON in this post. After JSON has been deserialized into a data structure, your question is about working with those structures, not JSON. Commented Feb 28, 2015 at 16:49

2 Answers 2

2

Try this

var baseLayers = {}
$.each(data, function(idx, obj) {
    baseLayers[obj.name] = new L.TileLayer(obj.url, {maxZoom: 18, id: obj.key, attribution: mbAttr});
});
Sign up to request clarification or add additional context in comments.

Comments

1

Without seeing what data looks like I believe you want:

var baseLayers = {};
$.each(data, function(idx, obj) {       
    baseLayers[obj.name] = new L.TileLayer(obj.url, {maxZoom: 18, id: obj.key, attribution: mbAttr});
});

You are trying to add an extra level which is not shown in your expected output

1 Comment

yes, there was an extra level just removed and it works. thanks!

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.