I Have next map:
const filter = new Map();
filter.set('a1', {
Day: 55,
Type: 1,
});
filter.set('a2', {
Day: 2,
Type: 3,
});
And next Array:
Data = [
{
points: 1,
event: 'a1',
},
{
points: 2,
event: 'a2',
},
]
I am new in JS, so it is not clear for me, how I can merge these by event
parameter? Expected output should be Map:
result = ['a1',
{
points: 1,
Day: 55,
Type: 1,
}],
['a2',
{
points: 2,
Day: 2,
Type: 3,
}],
you don't need reduce
here. better use map with es6 spread ...
operator for merging,
const filter = new Map(); filter.set('a1', { Day: 55, Type: 1, }); filter.set('a2', { Day: 2, Type: 3, }); const Data = [{ points: 1, event: 'a1', }, { points: 2, event: 'a2', }, ] const result = Data.map(o => [o.event, { points: o.points, ...filter.get(o.event) }]); console.log(result);
You could do something like the following:
const filter = new Map(); filter.set("a1", { Day: 55, Type: 1 }); filter.set("a2", { Day: 2, Type: 3 }); const data = [ { points: 1, event: "a1" }, { points: 2, event: "a2" } ]; const final = data.reduce((accumulator, item) => { // use destructing assignment to unpack values from the object const { event, points } = item; // get the appropriate event from the `filter` map by its event id const details = filter.get(event); // return a new array with the existing elements in `accumulator` // by using the `spread syntax` and append a new item/array // that has the `event` id in the first place, and an object // with the rest of the details in second place return [...accumulator, [ event, { points, ...details } ] ]; // start with an empty array }, []); console.log(final);
References:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.