根据地图创建数组

时间:2019-04-14 13:02:49

标签: javascript typescript

我有一张地图。检查地图上的连续键值,我需要分离键并插入新数组中。

let map = new Map<string, string>();
map.set("SUNDAY", "1");
map.set("MONDAY", "2");
map.set("TUESDAY", "2");
map.set("WEDNESDAY", "4");
map.set("THURSDAY", "5");
map.set("FRIDAY", "5");
map.set("SATURDAY", "9");

预期的输出应如下所示:

[{
      day: "SUNDAY",
      value: "1"
    },
    {
      day: "MONDAY-TUESDAY",
      value: "2"
    },
    {
      day: "WEDNESDAY",
      value: "4"
    },
    {
      day: "THURSDAY-FRIDAY",
      value: "5"
    },
    {
      day: "SATURDAY",
      value: "9"
    }
  ];

1 个答案:

答案 0 :(得分:2)

您可以reduce Map中的entries并根据value对其进行分组。如果累加器中已经存在当前value,则将-和当前day附加到对象。否则,向累加器添加一个新密钥。然后使用Object.values()以数组形式返回累加器的值

const map = new Map([["SUNDAY","1"],["MONDAY","2"],["TUESDAY","2"],["WEDNESDAY","4"],["THURSDAY","5"],["FRIDAY","5"],["SATURDAY","5"]]);

const merged = [...map].reduce((acc, [day, value]) => {
  if(acc[value])
    acc[value].day += `-${day}`
  else
    acc[value] = { day, value };
  
  return acc
}, {});

const output = Object.values(merged);

console.log(output)

更新

如果打字稿不允许您将Map散布到数组中,则可以在tsconfig(TypeScript and Iterator: Type 'IterableIterator' is not an array type)中将downlevelIteration设置为true

您也可以使用Map#forEach做同样的事情。另外,如果您希望day处于几天范围内,则可以使用另一个名为“ previousValue”的变量。如果previousValue与当前值相同,请拆分day中已经存在的-并获取第一个值。然后附加当前的day

let map = new Map([["SUNDAY","1"],["MONDAY","2"],["TUESDAY","2"],["WEDNESDAY","4"],["THURSDAY","5"],["FRIDAY","5"],["SATURDAY","5"]]);
let merged = {}, previousValue;

map.forEach((value, day) => {
  if(previousValue === value)
    merged[value].day = `${merged[value].day.split('-')[0]}-${day}`
  else
    merged[value] = { day, value };
  
  previousValue = value;
})

const output = Object.values(merged)

console.log(output)