If I have the following function that iterates through a json response object (val2):
function test(val2){
jQuery.each(val2.maps, function(j, val3) {
maps = new Array({
id: val2.maps[j].id,
parent: val2.maps[j].parent,
image: val2.maps[j].image,
data: val2.maps[j].data,
width: val2.maps[j].width,
height: val2.maps[j].height,
top: val2.maps[j].top,
left: val2.maps[j].left
})
});
return maps
}
how do I get it into an array that resembles the following format? Currently I’m only getting back the last array item.
maps = [{
id: 'south',
parent: 'us',
image: '/resources/images/maps/map_south.jpg',
data: 'popups/region_south.html',
width: '227px',
height: '177px',
top: '120px',
left: '49px'
},
{
id: 'east',
parent: 'us',
image: '/resources/images/maps/map_east.jpg',
data: 'popups/region_east.html',
width: '156px',
height: '121px',
top: '120px',
left: '283px'
}]
Cheers
Always fun when people post answers without explaining anything it seems to me that you don’t actually know what you’re doing here, so let me explain:
Here’s a fixed version, which actually does populate the array properly:
Also all your code has basically no effect, since all you’re doing is copying the elements of one array into another one without changing the structure in any way.
So in the end the values in both
val2.mapsand your returnedmapsare “identical”, only difference is that they do not point to the same objects since you copied all the values into new ones.If you don’t need a copy or you want to keep the reference to the original values, this would do it:
Nick has shown an even fancier version of doing the whole copying thing, but I thought it might help you more if someone would actually point out your mistakes, rather then posting even “crazier” jQuery code for you to copy&paste 😉
PS: Love my Firefox, Session just crashed but my answer was still here after the restart ^_^”