javascript - 在运行时在 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 的键时,原始数组也会被更新。
但正如预期的那样,它没有发生。
我的理解错了吗?在这种情况下,有没有更好的编码方法?
提前致谢。注意安全
解决方案
如果必须,您可以强制执行 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;
},{});
推荐阅读
- android - Theme.MaterialComponents.Light.DarkActionBar 打破 FAB 摇篮
- text - SwiftUI:文本视图连接如何使用 ForEach 循环或字符串数组执行此操作
- javascript - 如何解决 PHP Laravel 项目的语法错误或访问冲突?
- javascript - 我可以在没有 const 或强制转换的情况下使用 Typescript 字符串文字吗?
- wpf - WPF PropertyChangedEvent 始终为空
- c++-cli - 大批
^ 到 BYTE [] 精确转换 - google-cloud-platform - 如何在 terraform stackdriver 监控模板中添加 slack 团队频道
- sql - 如何查找A(一维数组)是否是B(二维数组)的一部分?
- r - 如何解释 mle() trace = 6 输出以及为什么 mle() 过程在 R 中的 101 次迭代后停止?
- python - OSError:异常:访问冲突读取 0x00007FFB1F945B50(随机发生)