-1

如何更改此 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"};
4

3 回答 3

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;
}
于 2013-03-24T23:04:45.880 回答
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.
于 2013-03-24T22:59:17.790 回答
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;
于 2013-03-24T22:59:24.977 回答