user6552641
user6552641

Reputation:

Javascript Change an array to look in a particular format

I have an array that's displaying on a particular format and I need it modified so that it displays on another format.

Here is the code:

var arr = {
    "id":"100",
        "name":"the name",
        "places":[
    {
        "id":"23",
        "name":"first place",
        "startDate":"2015-01-30 15:01:00",
        "endDate":"2015-01-30 17:01:00"
    },

    {
        "id":"54",
        "name":"second place",
        "startDate":"2015-01-31 17:01:00",
        "endDate":"2015-02-01 17:01:00"

    },
    {
        "id":"400",
        "name":"third place",
        "startDate":"2015-02-01 17:01:00",
        "endDate":"2015-02-05 17:01:00"

    }

]

}

var phases = mainData.places.map(function(e){
   return e.name + "," + 50;
});

myvar = [ places ];

This is displaying the data like this:

["first place,50", "second place,50", "third place,50"]

But I need to data to be displayed like this:

[ ['first place', 50],['second place', 50],['third place', 50] ];

How can I change the code so that it displays in the wanted format?

Upvotes: 1

Views: 45

Answers (1)

Pranav C Balan
Pranav C Balan

Reputation: 115212

Return the element as an array inside the Array#map method callback.

var phases = mainData.places.map(function(e){
   return [e.name , 50];
});

var arr = {
  "id": "100",
  "name": "the name",
  "places": [{
    "id": "23",
    "name": "first place",
    "startDate": "2015-01-30 15:01:00",
    "endDate": "2015-01-30 17:01:00"
  }, {
    "id": "54",
    "name": "second place",
    "startDate": "2015-01-31 17:01:00",
    "endDate": "2015-02-01 17:01:00"

  }, {
    "id": "400",
    "name": "third place",
    "startDate": "2015-02-01 17:01:00",
    "endDate": "2015-02-05 17:01:00"
  }]
}

var phases = arr.places.map(function(e) {
  return [e.name, 50];
});

console.log(phases);

Upvotes: 6

Related Questions