Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2-dimensional array to object (JavaScript)

I have an array, that holds a large number of two-dimensional arrays:

var myArray = [
    [2260146,2334221,"copy"],
    [1226218,2334231,"copy"],
    [2230932,-1,"copy"],
    [2230933,-1,"copy"],
    [2230934,-1,"copy"]
]

I need to convert this array into an object of the following form to send it as JSON:

var json = [
  {
    "s_id": 2260146,
    "t_id": 2334221,
    "type": "copy"
  },
  {
    "s_id": 1226218,
    "t_id": 2334231,
    "type": "copy"
  },
  {
    "s_id": 12,
    "t_id": -1,
    "type": "copy"
  }
]

("s_id" should be myArray[0][0], "t_id myArray[0][1], and "type" myArray[0][2] and so on.)

How can I get the array in the desired form? Thanks in advance.

like image 421
maze Avatar asked Jan 18 '13 11:01

maze


3 Answers

json = myArray.map(function(x) {
    return {    
        "s_id": x[0],
        "t_id": x[1],
        "type": x[2]
    }
})

Be aware that map is not supported in IEs < 9.

like image 172
georg Avatar answered Oct 26 '22 23:10

georg


You could destructure the parameter in map and use Shorthand property names:

const myArray=[[2260146,2334221,"copy"],[1226218,2334231,"copy"],[2230932,-1,"copy"],[2230933,-1,"copy"],[2230934,-1,"copy"]]

const output = myArray.map(([s_id, t_id, type]) => ({ s_id, t_id, type }))

console.log(output)
like image 21
adiga Avatar answered Oct 26 '22 23:10

adiga


Try with:

var length = myArray.length,
    json   = [];

for ( var i = 0; i < length; i++ ) {
  var subArray = myArray[i],
      item = {
        s_id: subArray[0],
        t_id: subArray[1],
        type: subArray[2]
      };
   json.push(item);
}
like image 20
hsz Avatar answered Oct 27 '22 00:10

hsz