简体   繁体   中英

Converting JSON/JS Object to array

I have a JSON response from my API that is structured like so:

{
  "data": [
    {
      "id": "1", "name": "test"
    },
    {
      "id": "2", "name": "test2"
    }
  ]
}

When I reference data I get the array with each record. I need the curly braces to be brackets due to a plugin I am using requiring it to be an array.

Desired output:

[
  ["1", "test"],
  ["2", "test"]
]

How can I convert the above JSON to this?

Edit:

This turned out to be a problem with a plugin I was using, and I knew how to do this fine all along. Thought I was going crazy but my code was fine, some plugin was screwing things up.

You can do this using Array.prototype.map

var arr = json.data.map(function(x){ 
   return [x.id, x.name]; 
});

Something like this maybe: http://jsfiddle.net/3gcg6Lbz/1/

var arr = new Array();
var obj = {
  "data": [
    {
      "id": "1", "name": "test"
    },
    {
      "id": "2", "name": "test2"
    }
  ]
}

for(var i in obj.data) {
  var thisArr = new Array();
  thisArr.push(obj.data[i].id);
  thisArr.push(obj.data[i].name);
  arr.push(thisArr);
}

console.log(arr);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM