const array = [
{ts: 1596232800, v1: 1},
{ts: 1596232860, v1: 2},
{ts: 1596232920, v1: 3},
{ts: 1596232800, b2: 10},
{ts: 1596232860, b2: 11},
{ts: 1596232920, b2: 12},
{ts: 1596232800, c3: 20},
{ts: 1596232860, c3: 21},
{ts: 1596232920, c3: 22}
];
我想合并数组中具有相同值 ts 的对象。我想要这个结果:
const result=[
{ts: 1596232800, v1: 1, b2: 10, c3: 20},
{ts: 1596232860, v1: 2, b2: 11, c3: 21},
{ts: 1596232920, v1: 3, b2: 12, c3: 22}
]
我试过这个:
const mergeArrayOfObjs = arr => Object.assign({}, ...arr);
const result = mergeArrayOfObjs(array);
console.log(result);
// Object { ts: 1596232920, v1: 3, b2: 12, c3: 22 }
我会使用一个临时对象来:
array
{...obj1, ...obj2}
)当前对象到res
在ts
键Object.values
将其转换为所需的阵列const array = [{ts: 1596232800, v1: 1}, {ts: 1596232860, v1: 2}, {ts: 1596232920, v1: 3}, {ts: 1596232800, b2: 10}, {ts: 1596232860, b2: 11}, {ts: 1596232920, b2: 12}, {ts: 1596232800, c3: 20}, {ts: 1596232860, c3: 21}, {ts: 1596232920, c3: 22} ];
let res = {};
array.forEach(a => res[a.ts] = {...res[a.ts], ...a});
res = Object.values(res);
console.log(res);
[
{
"ts": 1596232800,
"v1": 1,
"b2": 10,
"c3": 20
},
{
"ts": 1596232860,
"v1": 2,
"b2": 11,
"c3": 21
},
{
"ts": 1596232920,
"v1": 3,
"b2": 12,
"c3": 22
}
]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句