I basically want to do this in reverse: Convert multidimensional array to object
So let's say I have an object like this:
{
"6": {"10":{'id':0,'name':'player1'}},
"7": {"5":{'id':1,'name':'player2'}}
}
How can I convert that into a legit array like this:
[
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'}]
]
This is the code that I successfully used to convert it the other way around:
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));
asked Jul 25, 2016 at 13:01
Forivin
15.8k31 gold badges121 silver badges220 bronze badges
3 Answers 3
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;
}
answered Jul 25, 2016 at 13:20
apieceofbart
2,2074 gold badges25 silver badges37 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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))
answered Jul 25, 2016 at 13:18
Daniyal
3411 gold badge4 silver badges12 bronze badges
Comments
Based on your other question, assuming the source is json, you can use a revive function as well to convert the data directly when parsing
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);
answered Jul 25, 2016 at 14:04
Me.Name
12.6k3 gold badges34 silver badges48 bronze badges
Comments
Explore related questions
See similar questions with these tags.
lang-js
obj[7][5]returns{id: 1, name: "player2"}. The only difference, I guess, is that instead ofnullall unregistered array positions areundefined.obj[0]isundefined, so it has no first element.obj[0][0]would also throw an error with your new structure