如何基于AJAX响应动态创建ARRAY?

时间:2012-03-23 20:44:42

标签: javascript jquery ajax arrays

如何在获得AJAX响应后动态创建数组?

变量data.villages是我的回复。

我使用jQuery的每个函数循环它的值:

$.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

});

我的最终数组应如下所示:

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

我需要通过知道ID来获取名称值(或任何其他属性)....

您能否通过了解ID来向我展示如何获取此数据的示例?

3 个答案:

答案 0 :(得分:2)

要从json响应中创建对象数组,您应该可以执行以下操作:

var arrayOfObjects = [];

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

我认为你真正想要的是一个对象。您可以这样反对:

var objectFromJson= {};

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

答案 1 :(得分:0)

我认为你的最终阵列是错的:

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

必须是:

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

即一个数组,其对象的id = 234141,值为[{name:....}]

您可以通过以下方式实现这一目标:

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

答案 2 :(得分:0)

你可以试试像

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

你只是存储json