首页 > 解决方案 > 在运行时在 javascript 中更新 Map 的键

问题描述

我必须将父数组中的项目列表过滤到三个不同的数组中。

所以不要这样写:

this.otherList = parentArray.filter(e => e.type === OTHER);
this.adjustmentsList = parentArray.filter(e => e.type === ADJUSTMENTS);
this.sellerList = parentArray.filter(e => e.type === SELLER);

我想写出更好的编码风格。我正在阅读 ES6 的 Map 数据结构并想尝试一下。结果是这样的:

      const listConstantsMap = new Map([
            [this.otherList, OTHER],
            [this.adjustmentsList, ADJUSTMENTS],
            [this.sellerList, SELLER]
        ]);

        listConstantsMap.forEach((value, key) => {
            key = parentArray.filter(e => e.type === value);
        });

我将要更新的数组设置为键,并带有相应的字符串常量。我期待由于数组是通过引用复制的,所以每当我更新 Map 的键时,原始数组也会被更新。

但正如预期的那样,它没有发生。

我的理解错了吗?在这种情况下,有没有更好的编码方法?

提前致谢。注意安全

标签: javascript

解决方案


如果必须,您可以强制执行 MAP,但必须吗?

const listConstants = { other:{}, adjustments: {}, seller : {}}
Object.keys(listConstants).forEach(key => { 
  const KEY = key.toUpperCase();
  listConstants[key] = parentArray.filter(item => item.type === KEY);
});

使用减少

const keys = ["OTHER","ADJUSTMENTS","SELLER"]
const listConstants = parentArray.reduce((acc,item) => { 
  if (keys.includes(item.type)) {  
    const lc = item.type.toLowerCase(); // you can add "List" here if you need
    if (!acc[lc]) acc[lc] = [];
    acc[lc].push(item)
  }
  return acc;
},{});

推荐阅读