0

I have a javascript object and when I JSON.stringify it, it looks like following

[
    {
        "item_id": null,
        "parent_id": "none",
        "depth": 0,
        "left": "1",
        "right": 4
    },
    {
        "item_id": "1",
        "parent_id": null,
        "depth": 1,
        "left": 2,
        "right": 3
    }
]

I want to convert it to a multi-dimensional array which looks like the following

item[0][0] = item_id
item[0][1] = parent_id
item[0][2] = depth
item[0][3] = left
item[0][4] = right

item[1][0] = item_id
item[1][1] = parent_id
item[1][2] = depth
item[1][3] = left
item[1][4] = right

Any help will be much appreciated :)

Edit : Got it working with the help of all :) Thanks everybody for the help.

NishanCK
  • 57
  • 7

4 Answers4

4

Well lets take the initial object (array) prior to the stringify. With this we can loop each item. Then we can create a new array for each property. Something like this:

var myObject = X;//this is your original object
var newArray = [];

for(var i = 0; i < myObject.length; i++){
   var item = myObject[i];
   var subArray = [];
   subArray.push(item["item_id"]);
   subArray.push(item["parent_id"]);
   subArray.push(item["depth"]);
   subArray.push(item["left"]);
   subArray.push(item["right"]);
   newArray.push(subArray);
}

Here is a working example (check the console for the result)

NOTE: I purposefully avoided using a for in loop due to the rumours I always hear about the reliability of order. Of course, if you trust it then it's your call, but I prefer to play on the safe side. You can read some other opinions of this matter here.


If you want to increase the performance, you could create an array directly from the values, like so:

for (var i = 0; i < myObject.length; i++) {
    var item = myObject[i];
    var subArray = [item["item_id"], item["parent_id"], item["depth"], item["left"], item["right"]];
    newArray.push(subArray);
}

This is approximately twice as fast performance wise, here is the proof

Community
  • 1
  • 1
musefan
  • 47,875
  • 21
  • 135
  • 185
  • 1
    How about replacing lots of those lines with: `newArray.push(["item_id", "parent_id", "depth", "left", "right"].reduce(function(p, c) { return p.concat(item[c]); }, []));` – Amberlamps Jul 19 '13 at 08:35
  • 1
    @Amberlamps: No thanks, I like to make sure my answers can be understood by the OP ;-) – musefan Jul 19 '13 at 08:37
  • @Amberlamps: Also, yours appears slower than mine. I also did a third option which is faster than both. [Here are the results](http://jsperf.com/convert-objects-to-arrays) – musefan Jul 19 '13 at 08:45
  • @musefan: Yeah, performance-wise `reduce` seem to suck. An iterative solution seems always the best way to me. What is your third option? – Amberlamps Jul 19 '13 at 08:48
  • @Amberlamps: The third option was in my performance test link, but I have updated my answer to include it anyway – musefan Jul 19 '13 at 09:04
  • @musefan: This is nice! But now you can just put the array into the push function and omit the `subArray` variable after all. – Amberlamps Jul 19 '13 at 09:06
  • @Amberlamps: Indeed, I tested that too, but the performance was too close to be worth the readability hit. Infact, the first test I run it had slightly worse performance anyway, and the second test it was slightly better – musefan Jul 19 '13 at 09:09
1

Your "object" is actually an Array.

var item = [];
for (var i=0; i<yourArray.length; i++) {
   var subArray = [];
   var obj = yourArray[i];
   for (var j in obj) {
      subArray.push(j);
   }
   item.push(subArray);
}
Joe Beuckman
  • 2,264
  • 2
  • 24
  • 63
  • 2
    You should extract field value, not field name. – PA. Jul 19 '13 at 08:24
  • No, the question asks for field name. – Joe Beuckman Jul 19 '13 at 08:27
  • Actually the question is not really clear about that, but come on, it is kind of obvious that OP meant values not keys. – Amberlamps Jul 19 '13 at 08:30
  • @JoeBeuckman: It doesn't ask for field name. The example shows the field name as a variable. Which to me indicates they want the value of that field. Using field names would make no sense anyway – musefan Jul 19 '13 at 08:30
0

map your array elements by iterating over the fields of each of the objects

var item = yourarray.map(function (o) { 
  var s =[];
  for (var f in o) { 
    s.push(o[f]);
  }
  return s; 
});
PA.
  • 28,486
  • 9
  • 71
  • 95
-2

With recursion, for not limited dimensions of the data object:

fiddle

 function isArray($obj) {
    return Object.prototype.toString.call($obj) === '[object Array]';
}

function subObject(data) {


    if(isArray(data)){
        return (subArray(data));
    }

    var result = [];
    for (var i in data) {
        var item = data[i];
        if (item === null) { // null type is ojbect ..!
            result.push(item);
        } else if (isArray(item)) {
            result.push(subArray(item));
        } else if (typeof item === 'object') {
            result.push(subObject(item));
        } else {
            result.push(item);
        }
    }
    return result;
}

function subArray(data) {
    var result = [];

    for (var i = 0; i < data.length; i++) {
        var item = data[i]; 
        if (item === null) { // null type is ojbect ..!
            result.push(item);
        } else if (isArray(item)) {
            result.push(subArray(item));
        } else if (typeof item === 'object') {
            result.push(subObject(item));
        } else {
            result.push(item);
        }
    }
    return result;
}

var r = subObject(data);
console.log(r);
d.raev
  • 9,216
  • 8
  • 58
  • 79
  • 2
    Recursion is a little too much for this problem. OP is not saying anything about more dimensions. Also, the type of an array is "object"! – Amberlamps Jul 19 '13 at 08:27
  • this doesn't actually work. If throws a `null` reference error on one of the recursive calls – musefan Jul 19 '13 at 10:03
  • 1
    Do not use `for ... in` on arrays. To check whether a variable is an array or not use `Object.prototype.toString.call(item) === '[object Array]'` – Amberlamps Jul 19 '13 at 11:33
  • OK example works properly now. It is probably way more complex then the OP needs but it is good for reference. Thanks to @Amberlamps for the input. – d.raev Jul 19 '13 at 11:55