我基本上想反过来做:将多维数组转换为对象
假设我有一个这样的对象:
{
"6": {"10":{'id':0,'name':'player1'}},
"7": {"5":{'id':1,'name':'player2'}}
}
我如何才能将其转换为这样的合法数组:
[
null,
null,
null,
null,
null,
null,
[null, null, null, null, null, null, null, null, null, null, {'id':0,'name':'player1'}],
[null, null, null, null, null, {'id':1,'name':'player2'}]
]
这是我成功地将其转换为另一种方式的代码:
function populateFromArray(array) {
var output = {};
array.forEach(function(item, index) {
if (!item) return;
if (Array.isArray(item)) {
output[index] = populateFromArray(item);
} else {
output[index] = item;
}
});
return output;
}
console.log(populateFromArray(input));
function objectToArray(obj) {
var len = Math.max.apply(null, Object.keys(obj));
if (len !== len) return obj; // checking if NaN
var output = [];
for (var i = 0; i <= len; i++) {
output[i] = null;
if (obj[i]) {
output[i] = objectToArray(obj[i]);
}
}
return output;
}
var obj = {
"6": {"10":{'id':0,'name':'player1'}},
"7": {"5":{'id':1,'name':'player2'}}
};
function populateArray(obj) {
var range = 0,
arr = [];
for (var index in obj) {
range = Math.max(parseInt(index), range);
}
for (var i = 0; i <= range; i++) {
if (obj[i+'']) {
arr[i] = populateArray(obj[i+'']);
} else {
arr[i] = null;
}
}
return arr;
}
console.log(populateArray(obj))
基于您的另一个问题,假设源是json,您也可以在解析时使用revenue函数直接转换数据
var json = '{ "6": {"10":{"id":0, "name":"player1"}}, "7": {"5":{"id":1,"name":"player2"}}}';
function reviver(key,val){
if(isNaN(key) || val.id !== undefined)
return val;
var res = [];
for(var p in val)
res[p] = val[p];
return res;
}
var gameField = JSON.parse(json, reviver);
console.log(gameField);