我基本上想反过来做: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));
最佳答案
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;
}
关于javascript - 将对象转换为多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38568518/