Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transform Array of Objects (stringified) in JavaScript

I have this object in JavaScript of which the data is from AJAX response:

var data1 = [
   {
      "id": "ID1",
      "name": "John"
   },
   {
      "id": "ID2",
      "name": "Mark"
   },
];

How do I transform it to something like:

var data2 = [["ID1", "John"],["ID2", "Mark"]];

I need that format for populating the data to existing empty DataTables (row.add()).

Thank you for the help.

Edit: I added "ID1", and "ID2" to data2.

like image 419
Julez Avatar asked Nov 21 '25 09:11

Julez


2 Answers

If the AJAX response is not parsed yet, then make it an Object first

data1 = JSON.parse( ajaxResponseStr );

Assuming that data1 is already an Object, simply try

data2 = data1.map( function(item){ return [item.name] });
like image 130
gurvinder372 Avatar answered Nov 23 '25 00:11

gurvinder372


Use Array.prototype.map() to remove the unwanted fields and turn each object to the specified format, like this:

var data1 = [{
    "id": "ID1",
    "name": "John"
  },
  {
    "id": "ID2",
    "name": "Mark"
  },
];

var data2 = data1.map(function(item) {
  return [item["name"]];
});

console.log(data2);
like image 42
Angelos Chalaris Avatar answered Nov 22 '25 22:11

Angelos Chalaris