Calypo Gunn
Calypo Gunn

Reputation: 167

Populate array from an object array in javascript

I've got the following object that's an object array (an array of objects), on a variable:

variable: myVar1

On fireBug I get the following lines when I call myVar1:

[Object { myId= "1", myName= "Name1" }, Object { myId= "2", myName= "Name2" }, Object { myId= "3", myName= "Name3" }]

I need this data to be in the followng format stored on a variable too:

myVar2 = [
[1, 'Name1'],
[2, 'Name2'],
[3, 'Name3']
]

I've tried so many things like the use of for loops and js functions but can't get it work. I supose it's so easy. Anyone could try to explain the procedure.

Thank you

Upvotes: 2

Views: 228

Answers (2)

lawnsea
lawnsea

Reputation: 6581

The following should do the trick:

var myVar2 = [];
for (var i = 0; i < myVar1; i++) {
  myVar2.push([myVar1[i].myId, myVar1[i].myName]);
}

Upvotes: 1

VisioN
VisioN

Reputation: 145388

Solution for browsers which support Array.map():

var result = arr.map(function(o) { return [+o.myId, o.myName]; });

For compatibility you may use the shim provided at MDN.

Upvotes: 6

Related Questions