javascript - 根据内部条件以编程方式修改地图
问题描述
例如,我有一张这样的地图
const Map = new Map().set('123', [ [ 'foo', 'bar' ] ]).set('456', [ [ 'baz', 'qux' ], [ 'quux', 'corge' ] ]);
/*
The structure of the Map looks like this:
Map {
'123' => [ [ 'foo', 'bar' ] ],
'456' => [ [ 'baz', 'qux' ], [ 'quux', 'corge' ] ]
}
*/
我将如何删除数组中第一个嵌套元素 === 'quux' 的数组,以便它返回这个?
Map {
'123' => [ [ 'foo', 'bar' ] ],
'456' => [ [ 'baz', 'qux' ] ]
}
我知道如何通过执行删除项目
Map.set('456', (Map.get('456')).filter(array => array[0] !== 'quux'));
但这只是因为我知道哪个键('456')中包含带有'quux'的元素。我不确定如何以编程方式扫描地图,然后找到相应的键,然后删除该项目。Map 中的键和值将是动态的(但结构将是相同的),而要搜索的元素将是静态的,即:'quux',我的意思是 Map 中的内容可能会有所不同,我只是在执行搜索和删除。
解决方案
您可以遍历 的值Map
,findIndex
对每个值使用v
以查看它是否包含第一个元素为 的数组,如果是quux
,splice
则将该数组输出:
const map = new Map().set('123', [ [ 'foo', 'bar' ] ]).set('456', [ [ 'baz', 'qux' ], [ 'quux', 'corge' ] ]);
console.log("before", [...map]);
for (const v of map.values()) {
const index = v.findIndex((a) => a[0] === "quux");
if (index > -1) {
v.splice(index, 1);
}
}
console.log("after", [...map]);
这是非破坏性的替代方法,它通过获取旧 Map 的条目并将map
值 ping 到filter
我们不想要的数组来创建一个新的 Map:
const before = new Map().set('123', [ [ 'foo', 'bar' ] ]).set('456', [ [ 'baz', 'qux' ], [ 'quux', 'corge' ] ]);
console.log("before", [...before]);
const after = new Map([...before].map(([k, v]) => {
return [k, v.filter((a) => a[0] !== "quux")];
}))
console.log("after", [...after]);
注意:这两种方法之间的一个区别是第二种方法将删除所有具有quux
第一个元素的数组,而第二种方法将仅删除第一个这样的数组。当然,它们都可以进行更改以适应您需要的两个选项中的任何一个。
推荐阅读
- powershell - 如何使 powershell 作业返回我想要的对象类型?
- javascript - Paypal SDK,如何在不重新注入和重新初始化SDK本身的情况下动态更改货币?
- arcgis - 无法为 WebGL 要素图层创建标签,不支持 esriGeometryPolyline
- apache-tomee - 如何使用jar文件区分TomEE不同版本?
- javascript - IF 语句将变量值带入开关的问题
- java - 我需要在java中初始化一个地图列表,但是我尝试过的每一种方式都将它初始化为null
- h2 - 如何像 sql server 一样在 h2 中使用 getDate()
- rtsp - 从 ffmpeg 到 rtsp 格式的 Mp4 视频
- java - 如何使用带有 Java 的 chrome 选项在 Selenoid 中下载文件
- php - 如何在 4 列中显示查询结果并在 4 列之后移动到另一行?