A. Rossi A. Rossi - 6 months ago 15
Javascript Question

Javascript/Jquery JSON object to array inside object

I see many topics on this site, but every one deal with single Array.

My need is to convert every object with number as key to array.

For exemple,
I have an object like :

{
"parent":{
"0":{
"child":false
},
"1":{
"child":false
},
"4": {
"child":false
}
}
}


And i would like

{
"parent": [
{
"child":false
},
{
"child":false
},
null,
null,
{
"child":false
}
]
}


This is an exemple, my object can be really deep and content many object like this, so i need a generic function.

UPDATE

My try sor far using code of @Nenad Vracar :

function recursiveIteration(object) {
var newob = {};
for (var property in object) {
if (object.hasOwnProperty(property)) {
if (typeof object[property] == "object"){

var result = {};
var keys = Object.keys(object[property]);
if ($.isNumeric(keys[0])) {
console.log("======> "+property+" is table");

for (var i = 0; i <= keys[keys.length - 1]; i++) {
if (keys.indexOf(i.toString()) != -1) {
result[property] = (result[property] || []).concat(object[property][i]);
} else {
result[property] = (result[property] || []).concat(null);
}
}
newob[property] = result;
recursiveIteration(object[property]);
}


newob[property] = object[property];
recursiveIteration(object[property]);
}else{
newob[property] = object[property];
}
}
}
return newob;
}


And the JSFiddle for live try

Thanks you guys !

Answer

I think this is what you want:

var data = {
  "parent": {
    "0": {
      "child": false
    },
    "1": {
      "child": false
    },
    "4": {
      "child": false
    }
  }
};


var convert = function(data) {

  // not an object, return value
  if (data === null || typeof data !== 'object')
    return data;

  var indices = Object.keys(data);

  // convert children
  for (var i = 0; i < indices.length; i++)
    data[indices[i]] = convert(data[indices[i]]);

  // check if all indices are integers
  var isArray = true;
  for (var i = 0; i < indices.length; i++) {
    if (Math.floor(indices[i]) != indices[i] || !$.isNumeric(indices[i])) {
      isArray = false;
      break;
    }
  }

  // all are not integers
  if (!isArray) {
    return data;
  }
  // all are integers, convert to array
  else {
    var arr = [];
    for (var i = 0, n = Math.max.apply(null, indices); i <= n; i++) {
      if (indices.indexOf(i.toString()) === -1)
        arr.push(null);
      else
        arr.push(data[i]);
    }
    return arr;
  }

};

console.log( convert(data) );

Here is a working jsfiddle with the data you provided in the update.