更改数组格式

时间:2013-03-24 22:48:34

标签: javascript jquery arrays

如何更改此Javascript数组格式:

var sample_data = ["af","16.63","al","11.58","dz","158.97"];

到这种对象格式:

var sample_data = {"af":"16.63","al":"11.58","dz":"158.97"};

3 个答案:

答案 0 :(得分:2)

也可以使用Array.shift来做。不知道它如何与其他方法相比速度更快。

var sample_data = ["af","16.63","al","11.58","dz","158.97"]; // source

var data = sample_data.slice(); // clone the data

sample_data = {};

while (data.length > 1) {
    sample_data[data.shift()] = data.shift() || null;
}

答案 1 :(得分:1)

它的代码看起来像这样

var sample_data = ["af","16.63","al","11.58","dz","158.97"];
var tmp = sample_data;
sample_data = {};
for (var i = 0; i < tmp.length / 2; i++) 
    sample_data[tmp[i * 2]] = tmp[i * 2 + 1];

修改

请记住。

var arr = []; // This is an array
var obj = {}; // This is an object! Not array.

答案 2 :(得分:1)

var d = {}; // a temporary object
for (var i = 0; i < sample_data.length; i += 2) {
    // iterate over sample_data with a step width of 2
    // and set the the data in the temp. object
    d[sample_data[i]] = sample_data[i+1];
}
sample_data = d;