[英]How can I form an object with 2 array efficiently
I have 2 arrays我有 2 个 arrays
const x = [0, 1, 2, 3, 4, 5]
const y = [6, 7, 8, 9, 10, 11]
I'm trying to combine the two array into an array of objects such that it becomes:我正在尝试将这两个数组组合成一个对象数组,使其变为:
[{x: 0, y: 6}, {x: 1, y: 7}, {x: 2, y: 8}, {x: 3, y: 9}, {x: 4, y: 10}, {x: 5, y: 11}]
Currently what I did was to loop the length of one of the arrays then push the object to the new array.目前我所做的是循环 arrays 之一的长度,然后将 object 推送到新数组。
let newArray = []
for(i = 0; i < x.length; i++) {
newArray.push({x: x[i], y: y[i]})
}
Just wondering if there is a more efficient way to do this, thanks!只是想知道是否有更有效的方法来做到这一点,谢谢!
You can use map
to do the same thing.您可以使用
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)
And here is the same thing using 'reducer'这是使用“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)
You could go over an object and get the entries for having an array of objects.您可以通过 object 获取 go 并获取具有对象数组的条目。
This approach works as well for more arrays.这种方法也适用于更多的 arrays。
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; }
Your solution is good.你的解决方案很好。 Another way using
.map
:使用
.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]) );
Another way using for-loop
(to handle different list sizes):使用
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]) );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.