我基本上想反过来做这件事:Convert multidimensional array to object
所以我想说我有一个像这样的对象:
{
"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));
答案 0 :(得分:1)
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))
答案 1 :(得分:1)
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;
}
答案 2 :(得分:1)
基于你的other question,假设源是json,你也可以使用revive函数在解析时直接转换数据
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);