简体   繁体   中英

Create an array of arrays using for loop

My goal is to create an array that look something like this

var locations = [
    [
        "New Mermaid",
        36.9079,
        -76.199
    ],
    [
        "1950 Fish Dish",
        36.87224,
        -76.29518
    ]
]; 

I've tried

var data = $locations;
var locations = [];

for (i = 0; i < data.length; i++) {

  locations[i] =
  data[i]['name']+','+
  data[i]['lat']+','+
  data[i]['lng'];

}

console.log(locations);

I've got

["Apple  HQ,33.0241101,39.5865834", "Google MA,43.9315743,20.2366877"]

However that is not the exact format.


I want

var locations = [
    [
        "New Mermaid",
        36.9079,
        -76.199
    ],
    [
        "1950 Fish Dish",
        36.87224,
        -76.29518
    ]
];

How do I update my JS to get something like that ?

To build an "Array of arrays", this is one (of a few different methods):

for (i = 0; i < data.length; i++) {
  locations[i] = [];
  locations[i][0] = data[i]['name'];
  locations[i][1] = data[i]['lat'];
  locations[i][2] = data[i]['lng'];
}

or

for (i = 0; i < data.length; i++) {
  locations[i] = [data[i]['name'], data[i]['lat'], data[i]['lng']];
}
var locations = data.map(function(location){
  return [ location.name, location.lat, location.lng ];
}

Map will make an array with all the returned values from your function. Each return will be an array consisting of the 3 attributes you are looking for.

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