javascript - combine the object if the value of its field is the same [closed]
Solution 1:
This is really just a 'group by' by strike
with a computed property name based on type
.
const data = [ { id: 1, type: 'call', strike: 3000, volume: 50000 }, { id: 2, type: 'call', strike: 5000, volume: 30000 }, { id: 3, type: 'call', strike: 7000, volume: 20000 }, { id: 4, type: 'put', strike: 3000, volume: 50000 }, { id: 5, type: 'put', strike: 5000, volume: 10000 }, { id: 6, type: 'put', strike: 7000, volume: 7000 }, ];
const result = Object.values(
data.reduce((a, { type, strike, volume }) => {
(a[strike] ??= { strike })[`${type}Volume`] = volume;
return a;
}, {})
);
console.log(result);
Solution 2:
You could collect volume
by each group.
const
data = [{ id: 1, type: "call", strike: 3000, volume: 50000 }, { id: 2, type: "call", strike: 5000, volume: 30000 }, { id: 3, type: "call", strike: 7000, volume: 20000 }, { id: 4, type: "put", strike: 3000, volume: 50000 }, { id: 5, type: "put", strike: 5000, volume: 10000 }, { id: 6, type: "put", strike: 7000, volume: 7000 }],
result = Object.values(data.reduce((r, { type, strike, volume }) => {
r[strike] ??= { strike, callVolume: 0, putVolume: 0 };
r[strike][type + 'Volume'] += volume;
return r;
}, {}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }