我有一张这样的地图:
我想从地图值内的数组中删除{frequency:"WN"}
。
我正在尝试以这种方式将其删除,但价值并没有被删除:
const map2 = new Map();
map2.set(0, [{frequency:"DN"},{frequency:"WN"}, {frequency:"KK"}]);
map2.set(1, [{frequency:"DN"},{frequency:"WN"}, {frequency:"KK"}]);
const strNanFrq = ['DN', 'WN', 'MN', 'QN', 'YN'];
for (tsRequest of map2.values()) {
tsRequest.filter((req, index) => {
if (strNanFrq.includes(req['frequency'])) {
tsRequest.splice(index, 1);
}
});
}
console.log(Array.from(map2.values())); // still has all the values in map
答案 0 :(得分:1)
您可以循环访问Map
和filter
的每个值,以删除frequency
中包含的strNanFrq
的对象。为strNanFrq
创建一个Set
,并检查集合has
是否是当前对象的频率。
const map = new Map([
[0, [{ frequency:"DN" },{ frequency:"WN" }, { frequency:"KK" } ]],
[1, [{ frequency:"YN" },{ frequency:"AA" }, { frequency:"BB" } ]],
]);
const strNanFrq = new Set(['DN', 'WN', 'MN', 'QN', 'YN']);
for (const [key, value] of map)
map.set(key, value.filter(v => !strNanFrq.has(v.frequency)))
console.log(map.get(0))
console.log(map.get(1))
答案 1 :(得分:-1)
再次使用前一个数组的过滤后的数组设置映射值。 如果地图中还有更多数组,请使用forEach遍历地图键值对,并检查该值是否实际上是一个数组,并使用filter对其进行重置:
var map2 = new Map();
map2.set(0, [{frequency:"DN"},{frequency:"WN"}, {frequency:"KK"}]);
map2.set(1, [{frequency:"DN"},{frequency:"WN"}, {frequency:"KK"}]);
map2.forEach((val, key) => {
if (Array.isArray(val)) {
map2.set(key, val.filter(el => el.frequency !== 'WN'));
}
});
console.log(map2.values());