如何解决合并传感器数据数组的最佳方法
我正在使用AHRS库来创建传感器融合的位置数据数组。
从Go Pro遥测数据中,我得到了加速度计,陀螺仪和磁力计数据阵列,并为每个具有以下形状的样本添加了时间戳:
{
ACCEL: {
samples: [{time,data},...]
},....
}
我想将它们合并成一个对象
{
time: {accel,gyro,magn}
...
}
每个时间戳具有全部3个值
我已经与减速器一起使用
const magn = result[1].streams['MAGN'].samples.reduce((prev,next) => {
return {...prev,[next.cts]: {magn: next.value}}
},{})
const gyro = result[1].streams['GYRO'].samples.reduce((prev,next) => {
const closest = prev[Object.keys(prev).reverse()?.find(key => key < next.cts) || Object.keys(prev)[0]]
return {...prev,[next.cts]: {...closest,gyro: next.value}}
},magn)
const merged = result[1].streams['ACCL'].samples.reduce((prev,accel: next.value}}
},gyro)
但这似乎不是很优雅的代码。
有没有更有效的方法来处理它?
解决方法
打字稿playground
type Input = Record<string,{ samples: { time: number,data: any }[] }>
type Output = Record<'number',{ [K in keyof Input]: any }>
const inp: Input = { ACCEL: { samples: [{ time: 12,data: '12data' },{ time: 14,data: '14data' }]},GYRO: { samples: [{ time: 18,data: 'gyro18' },{ time: 12,data: 'gyro12' }] }};
const keyOfInput = Object.keys(inp)
const collectionOfTimes = [
... new Set(
keyOfInput
.map(key => inp[key].samples.map(s => s.time))
.reduce((acc,curr) => [...acc,...curr],[]))
]
const out: Output = collectionOfTimes.reduce((acc,time) => ({ ...acc,[time]:
keyOfInput.reduce((acc2,key) => ({...acc2,[key]: inp[key].samples.find(i => i.time === time)?.data || null}),{})
}),{} as Output);
console.log(out);
/*
[LOG]: { "12": { "ACCEL": "12data","GYRO": "gyro12" },"14": { "ACCEL": "14data","GYRO": null },"18": { "ACCEL": null,"GYRO": "gyro18" } }
*/
在typescriptlang.org上编译为js
"use strict";
const inp = { ACCEL: { samples: [{ time: 12,data: '14data' }] },data: 'gyro12' }] } };
const keyOfInput = Object.keys(inp);
const collectionOfTimes = [
...new Set(keyOfInput
.map(key => inp[key].samples.map(s => s.time))
.reduce((acc,[]))
];
const out = collectionOfTimes.reduce((acc,time) => (Object.assign(Object.assign({},acc),{ [time]: keyOfInput.reduce((acc2,key) => { var _a; return (Object.assign(Object.assign({},acc2),{ [key]: ((_a = inp[key].samples.find(i => i.time === time)) === null || _a === void 0 ? void 0 : _a.data) || null })); },{}) })),{});
console.log(out);
/*
[LOG]: { "12": { "ACCEL": "12data","GYRO": "gyro18" } }
*/
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。