CeoDeveloper
CeoDeveloper

Reputation: 27

How to dynamically create a ARRAY based on a AJAX response?

How do I dynamically create a array after getting a AJAX response ?

The variable data.villages is my response.

I loop over its value using the jQuery each function:

$.each(data.villages, function(key, value) { 

   //Here I have the 2 variables: value.id and value.name

   //Now I need to build a array where the value.id is the KEY and the content is name : value.name

  //After I need to create an array with all the arrays

});

My final array should look like this:

[ 234141 : [{ name: 'vila1', othervariable: 'othervalue' }] ]

I need this to get the name value (or any other property) by knowing the ID....

Can you also show me example on how to get this data by knowing the ID ?

Upvotes: 0

Views: 5273

Answers (3)

j-u-s-t-i-n
j-u-s-t-i-n

Reputation: 1452

To create an array of objects from your json response you should be able to do something like this:

var arrayOfObjects = [];

for (var i = 0, var dataLength = data.villages.length; i < dataLength; i++) {
      arrayOfObjects.push(data.villages[i]);
}

What I think you actually want is an object. You can object like so:

var objectFromJson= {};

for (var i = 0, var dataLength = data.villages.length; i < dataLength; i++) {
      var currentItem = data.villages[i];
      objectFromJson[currentItem.WhatEverPropertyYouWantForTheKey] = currentItem;
}

Upvotes: 2

gastonfartek
gastonfartek

Reputation: 348

you could try something like

arr = new Array();
arr[value.key] = {var1: 'vila1', var2: 'vila2'};

you are just storing json

Upvotes: 0

acanimal
acanimal

Reputation: 5020

I think your final array is wrong:

[ 234141 : [{ name: 'vila1', othervariable: 'othervalue' }] ]

must be:

[ 
    { 234141 : [{ name: 'vila1', othervariable: 'othervalue' }] }
]

that is, an array with an object with the id=234141 and value [{name: ....}]

You can achieve that with:

data.villages = "your returned data array";
var newArray = [ { 234141: [] } ];
$.each(data.villages, function(key, value) {
    newArray[0]['234141'].push({key: value};
}

Upvotes: 0

Related Questions