この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"};
この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"};
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;
}
そのためのコードは次のようになります
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.
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;