如何有效地用2个数组组成一个对象?



我有两个数组

const x = [0, 1, 2, 3, 4, 5]
const y = [6, 7, 8, 9, 10, 11]

我试图将这两个数组组合成一个对象数组,这样它就变成了:

[{x: 0, y: 6}, {x: 1, y: 7}, {x: 2, y: 8}, {x: 3, y: 9}, {x: 4, y: 10}, {x: 5, y: 11}]

目前我所做的是循环其中一个数组的长度,然后将对象推入新数组。

let newArray = []
for(i = 0; i < x.length; i++) {
newArray.push({x: x[i], y: y[i]})
}

只是想知道是否有更有效的方法来做到这一点,谢谢!

你的解决方案很好。另一种使用.map:

的方法

const getCoordinates = (xCoordinates=[], yCoordinates=[]) =>
xCoordinates.map((x,index) => ({x, y:yCoordinates[index]}));
console.log( getCoordinates([0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11]) );

使用for-loop的另一种方法(处理不同的列表大小):

const getCoordinates = (xCoordinates=[], yCoordinates=[]) => {
const coordinates = [];
for(let i = 0, j = 0; i < xCoordinates.length && j < yCoordinates.length; i++, j++)
coordinates.push({x:xCoordinates[i], y:yCoordinates[i]});
return coordinates;
}
console.log( getCoordinates([0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11]) );

您可以遍历一个对象并获得拥有一个对象数组的条目。

这个方法也适用于更多的数组。

const
x = [0, 1, 2, 3, 4, 5],
y = [6, 7, 8, 9, 10, 11],
result = Object
.entries({ x, y })
.reduce((r, [k, a]) => a.map((v, i) => ({ ... r[i], [k]: v })), []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

您可以使用map做同样的事情。

const x = [0, 1, 2, 3, 4, 5]
const y = [6, 7, 8, 9, 10, 11]
const newArray = x.map((number, index) => ({x: number, y: y[index]}));
console.log(newArray)

这里用的是reducer

const x = [0, 1, 2, 3, 4, 5]
const y = [6, 7, 8, 9, 10, 11]

const newArray = x.reduce((arr, n, index) => {
arr.push({x: n, y: y[index]});
return arr;
}, [])
console.log(newArray)

最新更新