Edward Edward - 3 months ago 10
jQuery Question

Convert JSON from MVC controller to array in jQuery

I have a controller in MVC, and return JSON like below:

public JsonResult getData()
{
var data = new[]{
new
{
x = 10,
y = 20,
name = "Jim",
},
new
{
x = 11,
y = 21,
name = "Tom",
}
};

return Json(data, JsonRequestBehavior.AllowGet);
}


And I have AJAX request like below:

$.ajax({
type: "GET",
url: "https://localhost:44361/home/getdata",
dataType: "json",
success: function (result) {
return result;
},
error: function (response) {
return "faut";
}
});


I want to convert the JSON result to below Array

var arr = [
['x','y','name'],
[10,20,'Jim'],
[11,21,'Tom']
];

Answer

Try this code:

const arr = [Object.keys(result[0])]
  .concat(result.map(({x, y, name}) => [x, y, name]))

Alternative, cross-browser solution:

const arr = [Object.keys(result[0])]
  .concat(result.map(function(obj) {
    return [obj.x, obj.y, obj.name]
  }))
Comments