Forivin
Forivin

Reputation: 15488

Convert object to multidimensinal array

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));

Upvotes: 1

Views: 76

Answers (3)

Me.Name
Me.Name

Reputation: 12534

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);

Upvotes: 1

apieceofbart
apieceofbart

Reputation: 2197

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;
}

Upvotes: 1

Daniyal
Daniyal

Reputation: 341

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))

Upvotes: 1

Related Questions