通过键合并地图和对象数组

时间:2020-07-22 10:17:55

标签: javascript arrays

我有下一张地图:

 const filter = new Map();

  filter.set('a1', {
    Day: 55,
    Type: 1,
  });

  filter.set('a2', {
    Day: 2,
    Type: 3,
  });

下一个数组:

Data = [
    {
      points: 1,
      event: 'a1',
    },
    {
      points: 2,
      event: 'a2',
    },
  ]

我是JS的新手,所以我不清楚,如何通过event参数合并它们? 预期输出应为Map:

   result = ['a1',
    {
      points: 1,
      Day: 55,
      Type: 1,
    }],
    ['a2',
    {
      points: 2,
      Day: 2,
      Type: 3,
    }],

2 个答案:

答案 0 :(得分:3)

您在这里不需要reduce。更好地使用map 使用es6 spread ...运算符进行合并,

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

答案 1 :(得分:2)

您可以执行以下操作:

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

参考: