Javascript 点对象数组到X和Y数组

Javascript 点对象数组到X和Y数组,javascript,ecmascript-6,Javascript,Ecmascript 6,我有一个点对象数组: const points = [ {x: 0, y: 0 }, { x: 1, y: 1}, ...] 我想将它们转换为x和y的数组: const x = [0, 1, ...]; const y = [0, 1, ...]; 我可以使用2张地图: const x = points.map(v => v.x); const y = points.map(v => v.y); 但这需要在阵列上进行2次迭代。我可以做一个循环: const x = []; co

我有一个
对象数组:

const points = [ {x: 0, y: 0 }, { x: 1, y: 1}, ...]
我想将它们转换为x和y的数组:

const x = [0, 1, ...];
const y = [0, 1, ...];
我可以使用2张地图:

const x = points.map(v => v.x);
const y = points.map(v => v.y);
但这需要在阵列上进行2次迭代。我可以做一个循环:

const x = [];
const y = [];
for (let i = 0; i < points.length; ++i) {
   const pt = points[i];
   x.push(pt.x);
   y.push(pt.y);
}
const x=[];
常数y=[];
对于(设i=0;i
这似乎过于冗长,而且可能很慢(所有这些推回)。
有更好的方法吗?

至少你需要一些推送到想要的结果集。此解决方案使用对象推送到右侧阵列

const
点=[{x:0,y:0},{x:1,y:1}],
x=[],
y=[],
值={x,y};
points.forEach(o=>Object.entries(o).forEach(([k,v])=>value[k].push(v));
控制台日志(x);

控制台日志(y)至少你需要一些推送到想要的结果集。此解决方案使用对象推送到右侧阵列

const
点=[{x:0,y:0},{x:1,y:1}],
x=[],
y=[],
值={x,y};
points.forEach(o=>Object.entries(o).forEach(([k,v])=>value[k].push(v));
控制台日志(x);

控制台日志(y)好的,您可以这样做:

const points=[{x:0,y:0},{x:1,y:1}];
const t=points.map(项=>{
返回对象。值(项);
})
常数x=t[0];
常数y=t[1];

控制台日志(x,y)好的,您可以这样做:

const points=[{x:0,y:0},{x:1,y:1}];
const t=points.map(项=>{
返回对象。值(项);
})
常数x=t[0];
常数y=t[1];

控制台日志(x,y)虽然您可以很容易地做到这一点,但可以这样说:

const points=[{x:1,y:2},{x:2,y:3},{x:3,y:5},{x:4,y:7},{x:5,y:11}]
常数{x,y}=points.reduce(
({x,y},pt)=>({x:[…x,pt.x],y:[…y,pt.y]}),
{x:[],y:[]}
)
console.log(x)

console.log(y)
虽然您可以很容易地做到这一点,但可以这样说:

const points=[{x:1,y:2},{x:2,y:3},{x:3,y:5},{x:4,y:7},{x:5,y:11}]
常数{x,y}=points.reduce(
({x,y},pt)=>({x:[…x,pt.x],y:[…y,pt.y]}),
{x:[],y:[]}
)
console.log(x)
console.log(y)
您可以使用
数组#reduce
在多维数组中累积结果

const points=[{x:0,y:0},{x:1,y:1}],
[x,y]=点数减少((r,o)=>{
Object.values(o).forEach((v,i)=>r[i].push(v));
返回r;
},[[],[]]);
控制台日志(x);
控制台日志(y)
您可以使用
数组#reduce
在多维数组中累积结果

const points=[{x:0,y:0},{x:1,y:1}],
[x,y]=点数减少((r,o)=>{
Object.values(o).forEach((v,i)=>r[i].push(v));
返回r;
},[[],[]]);
控制台日志(x);

控制台日志(y)
记住,内部到
映射
推送
相当的事情无论如何都会发生。您是否已经测试并发现这两个迭代导致了显著的减速?请记住,
map
的内部操作与
push
相当的操作无论如何都会发生。您是否测试并发现这两个迭代会导致您的速度显著降低?是的-我正在将点数组从React plotly库传递给React组件。它需要一个X数组和一个Y数组数据。这很有意义。这里的许多技术都会对您有所帮助,但如果两个单独的
map
调用实际上更快,我也不会感到惊讶。是的,我正在将点数组从React plotly库传递给React组件。它需要一个X数组和一个Y数组数据。这很有意义。这里的许多技术都会对您有所帮助,但如果两个单独的
map
调用实际上更快,我也不会感到惊讶。
var x= [], y = [], points = [{ x: 0, y: 0 }, { x: 1, y: 10 }];

points.forEach(({x: x1, y: y1}) => (x.push(x1), y.push(y1)))

console.log(x, y)