TransWikia.com

merge Map and Array of objects by key

Stack Overflow Asked on November 22, 2021

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,
    }],

2 Answers

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);

Answered by Thomas on November 22, 2021

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:

Answered by goto1 on November 22, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP