0

我正在使用 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, next) => {
    const closest = prev[Object.keys(prev).reverse()?.find(key => key < next.cts) || Object.keys(prev)[0]]
    return {...prev, [next.cts]: {...closest, accel: next.value}}
}, gyro)

但这似乎不是非常优雅的代码。

有没有更有效的方法来处理它?

4

1 回答 1

0

打字稿游乐场

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: '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 = 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": "gyro12" }, "14": { "ACCEL": "14data", "GYRO": null }, "18": { "ACCEL": null, "GYRO": "gyro18" } }
*/ 
于 2020-10-13T20:54:34.530 回答