数组转换问题

时间:2011-04-12 14:05:24

标签: javascript

我下面有一个数组,

var array = {
    "Id":[1,2,3],
    "Name":["one","two","five"],
    "row":[8,9,7]
}

但我想将其转换为

var array2 = 
{"data":
    [
    {"Id":1,"Name":"one","Row:8"},
    {"Id":2,"Name":"two","Row:9"},
    {"Id":3,"Name":"five","Row:7"},
    ]
}

这可能吗?

3 个答案:

答案 0 :(得分:2)

这应该这样做:

// make sure the new object is initialized
var array2 = { data: [] };
// Count the number of items in array.Id and start iterating
for (var i=0,t=array.Id.length; i < t; i++) {
   // Note that array.Id = [1,2,3] does not result in corresponding keys
   // array.Id[0] corresponds to value 1!
   array2.data.push({
       Id: array.Id[i],
       Name: array.Name[i],
       Row: array.Row[i]
   });
}

答案 1 :(得分:1)

var array2 = {data: []};
for (i in array.Id) {
    array2.data.push({
        Id: array.Id[i],
        Name: array.Name[i],
        row: array.row[i]
    });
}

没试过它

答案 2 :(得分:0)

它不是一个数组。这是一个对象。

var myArr = [1,2,3]; //Array definition


var myObj = {test:"1",test2:"2"}; //Object Definition



var array = [1,[1,2,3]]; // multidimensional array