简体   繁体   中英

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 ?

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

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

you could try something like

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

you are just storing json

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM