将数组推入对象

Jef*_*eff 3 javascript arrays object

我有三个相同大小的数组lat[], lon[], title[].我需要以这种格式创建一个对象

locations = [
    {
        lat: 45.4654,
        lon: 9.1866,
        title: 'Milan, Italy'
    },
    {
        lat: 47.36854,
        lon: 8.53910,
        title: 'Zurich, Switzerland'
    },
    {
        lat: 48.892,
        lon: 2.359,
        title: 'Paris, France'
    }
];
Run Code Online (Sandbox Code Playgroud)

到目前为止我已经这样做了

  var locations = {};
  var lat = [1, 2, 3];
  var lon = [4, 5, 6];
  var title = ['title 1', 'title 2', 'title 3'];
  var numLocation = $lat.length;

  for (var j=0; j < numLocation; j++) {

    locations[j] = {};
    locations[j].lat = lat[j];
    locations[j].lon = lon[j];
    locations[j].title = title[j];
  }
Run Code Online (Sandbox Code Playgroud)

但是Object { 0={...}, 1={...}, 2={...}, more...} 当我需要一个这样的物体时, 我会得到一个这样的物体 [Object { lat=45.4654, lon=9.1866, title="Milan, Italy", more...}, Object { lat=47.36854, lon=8.5391, title="Zurich, Switzerland", more...}, Object { lat=48.892, lon=2.359, title="Paris, France", more...}, Object { lat=48.13654, lon=11.57706, title="Munich, Germany", more...}]

对不起,如果我不使用技术术语,但我真的不知道很多JavaScript,我只是日复一日地学习它.我希望有人能帮帮忙.

Dar*_*rov 9

假设所有的lat[],lon[]并且title[]阵列具有所有相同的大小,则可以尝试来定义locations变量作为基于0的整数索引阵列([]),而不是一个javascript对象({}):

var locations = [];
for (var i = 0; i < lat.length; i++) {
    locations.push({
        lat: lat[i],
        lon: lon[i],
        title: title[i]
    });
}
Run Code Online (Sandbox Code Playgroud)

当然,您应该检查所有3个阵列是否具有相同的大小,只需确定,您知道:

var length = lat.length;
if (lon.length !== length || title.length !== length) {
    alert('Sorry, but the operation you are trying to achieve is not well defined');
}
Run Code Online (Sandbox Code Playgroud)