首页 > 解决方案 > 根据内部条件以编程方式修改地图

问题描述

例如,我有一张这样的地图

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 中的内容可能会有所不同,我只是在执行搜索和删除。

标签: javascriptdictionaryecmascript-6

解决方案


您可以遍历 的值MapfindIndex对每个值使用v以查看它是否包含第一个元素为 的数组,如果是quuxsplice则将该数组输出:

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第一个元素的数组,而第二种方法将仅删除第一个这样的数组。当然,它们都可以进行更改以适应您需要的两个选项中的任何一个。


推荐阅读