如何在 Javascript 中将 2 个数组合并为 1 个数组?
2021-01-26
77
我想将我的数组合并为一个,同时在其中创建不同的对象。 我想要实现的结果是:
[{latitude: 19.04890787659077,longitude: 47.49627131324106}, {latitude: 19.07438856746581, longitude: 47.49834420053164}, {etc..}]
我当前的数组如下所示:
0: 19.04890787659077
1: 18.93150306374864
2: 18.570734077493597
3: 17.948338720442376
4: 18.594379058124062
0: 47.49627131324106
1: 47.44522085405608
2: 47.482922755413774
3: 47.31701880320728
4: 46.052752331223935
数据将是动态的,所以我无法通过 [{latitude: Arr[0], longitude: Arr[5]}, {etc..}] 来解决它
3个回答
const arr1 = [
19.04890787659077,
18.93150306374864,
18.570734077493597,
17.948338720442376,
18.594379058124062
];
const arr2 = [
47.49627131324106,
47.44522085405608,
47.482922755413774,
47.31701880320728,
46.052752331223935
];
const result = arr1.map((v, i) => ({
latitude: v,
longitude: arr2[i]
}));
console.log(result);
Pedro Lima
2021-01-26
我不是 100% 确定您的意思,但我认为您正在寻找以下之一:
Array.prototype.push.apply(arr1,arr2);
或
arr1 = arr1.concat(arr2)
这些是老派方法,新方法是
var arr3 = [...arr1, ...arr2]
ptts
2021-01-26
如果你只有一个这样的数组:
const a = [19, 18, 17, 18, 19, 47, 46, 46, 47, 47];
我试过这个:
const mid = Math.floor(a.length/2);
const result = a.slice(0, mid).map((el, idx) => ({lat:el, lon:a[idx+mid]}))
Max
2021-01-26