3

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.

7 Answers 7

4

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] });
Sign up to request clarification or add additional context in comments.

1 Comment

This answer and those below ones are all useful and acceptable but I have to accept only one. To be fair, I'd accept this since this is the first. Thanks, all.
2

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);

Comments

1

Your data1 is an Array, so you can easily use .map method on it. .map method returns an Array of values, you return from callback.

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

Comments

1

basing on your data structure, coding like this:

var data2 = [];
for(var i in data1){
    data2.push(data1[i].name)
}

Comments

1

Simply use Array.prototype.map().

ES6:

const data2 = data1.map(({ name }) => [name]);

ES5:

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

Comments

1

Or using Array.prototype.reduce();

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

var data2 = data1.reduce(function(accum, item) { accum.push([item.name]); return accum; }, []);
console.log(data2);

Comments

1

You can use array#map to create an array of names and id.

EDIT: OP updated the question. Code edited to return both id and name.

var data1 = [{"id": "ID1","name": "John"},{"id": "ID2","name": "Mark"}];
var data2 = data1.map(({id, name}) => [id, name]);
console.log(data2);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.