javascript - 使用“map”函数返回多个数组
问题描述
我的代码有一个元素数组,如下所示:
element: { fromX: { id: ... } , toX: { id: ... } }
要求是将所有fromX
id 拉到一个数组中,并将所有toX
id 拉到另一个数组中。
有几种不同的方法,例如使用foreach
, reduce
, 分别为每种方法进行迭代,但是我正在寻找一种最佳的功能方法来返回具有一个映射的两个数组?
解决方案
const data=[{fromX:{id:1},toX:{id:2}},{fromX:{id:3},toX:{id:4}},{fromX:{id:5},toX:{id:6}},{fromX:{id:7},toX:{id:8}}]
const [fromX,toX] = data.reduce(([a,b], {fromX,toX})=>{
a.push(fromX.id);
b.push(toX.id);
return [a,b];
}, [[],[]]);
console.log(fromX);
console.log(toX);
推荐阅读
- java - 将 JSON 转换为 GSON 到 Android
- ios - 从 Bluez 5.48 开始,iPhone 在连接 BLE GAP 外围设备时需要配对,为什么?
- google-chrome - Chrome 扩展程序被 Chrome 禁用
- php - 如何在php中将零存储在数组中
- swift - 从一个 UTM 区域到另一个 UTM 区域的投影点
- javascript - TypeORM:如何使用 UUID 获取下一个项目?
- java - 无法从 Java WebSocket 向 JS 客户端发送消息
- python - 在 numpy 数组中的所有项目周围添加 0
- node.js - 电极点燃 - 生成应用程序 - 类型错误:无法读取未定义的属性“代理”
- java - 委托人获取用户ID