0

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 !

9
  • And what have you tried to achieve it ? Commented Jun 2, 2016 at 7:35
  • what is null, null? Commented Jun 2, 2016 at 7:38
  • What do you mean by deep?Is there any nesting to nth level? Commented Jun 2, 2016 at 7:39
  • @Rahul Arora null, null, is index 2 and 3. Commented Jun 2, 2016 at 7:40
  • @RIYAJ KHAN I mean i can have object, in object in object, etc... Commented Jun 2, 2016 at 7:41

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Hey man, that's perfect, thanks you so much, and thanks to everyone try to help me !
0

You can do this with Object.keys() and one for loop

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

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

console.log(result)

1 Comment

Thats the idea ! But as i said i need a generic function for doing it, key are never the same, etc...But thanks, i'll try to do it based on your code.
0

You might achieve this job with a very simple recursive Object method as follows. Any valid nested object (including arrays) within an object structure will be converted into an array, in which the properties are replaced with indices and values are replaced by items.

Object.prototype.valueToItem = function(){
  return Object.keys(this).map(e => typeof this[e] === "object" &&
                                           this[e] !== null     &&
                                    !Array.isArray(this[e]) ? this[e].valueToItem()
                                                            : this[e]);
};

var o = {    name: "terrible",
         lastname: "godenhorn",
             cars: ["red barchetta", "blue stingray"],
              age: 52,
            child: {    name: "horrible",
                    lastname: "godenhorn",
                        cars: ["fiat 124", "tata"],
                         age: 24,
                       child:{    name: "badluck",
                              lastname: "godenhorn",
                                  cars: ["lamborghini countach"],
                                   age: 2,
                                 child: null}}},
a = o.valueToItem();
console.log(a);

Ok modified to the OP's conditions but still generic as much as it can be.

Object.prototype.valueToItem = function(){
  var keys = Object.keys(this);
  return keys.reduce((p,c) => typeof this[c] === "object" &&
                                     this[c] !== null     &&
                              !Array.isArray(this[c]) ? keys.every(k => Number.isInteger(k*1)) ? (p[c] = this[c].valueToItem(),p)
                                                                                               : this[c].valueToItem()
                                                      : this
                     ,new Array(~~Math.max(...keys)).fill(null));
};

var o = {
	     parent: {
	              0: {
	              	  child : false
	              },
	              1: {
	              	  child : false
                  },
	              4: {
	              	  child : {
	                           0: {
	              	               child : false
	                           },
	                           3: {
	              	               child : false
                               },
	                           5: {
	              	               child : false
	                           }
	              	  }
	              }
	     }
};
a = o.valueToItem();
console.log(JSON.stringify(a,null,4));

5 Comments

This will convert every object to an array, effectively losing all property names.
@janje Exactly... this is what it does. That's why it's called valueToItem()
That is not what the OP wants to do. Check my answer for the correct behaviour.
Yeah, this is not exactly what i want, but your code is interesting. If i had a better knowledge on javascript i could edit it for my need, but i'm not good enought for it :/
@A. Rossi OK have corrected the above code according to what i think you want :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.