Javascript 基于内部条件以编程方式修改贴图

Javascript 基于内部条件以编程方式修改贴图,javascript,dictionary,ecmascript-6,Javascript,Dictionary,Ecmascript 6,例如,我有一张这样的地图 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',

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

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')中有带'quox'的元素。我不确定如何以编程方式扫描映射,然后找到相应的键,然后删除该项。映射中的键和值将是动态的(但结构将是相同的),而要搜索的元素将是静态的,即:“quux”,我的意思是映射中的内容可能会有所不同,我只是执行搜索和删除。

您可以循环搜索
映射的值,在每个值
v
上使用,查看它是否包含第一个元素为
qux
的数组,如果是,则查看该数组:

const-map=new-map().set('123',[[['foo','bar']]).set('456',[['baz','qux'],['qux','corge']]);
log(“before”,[…map]);
for(map.values()的常数v){
常数索引=v.findIndex((a)=>a[0]==“qux”);
如果(索引>-1){
v、 拼接(索引1);
}
}

log(“之后,[…映射])您可以迭代映射,如果找到想要的值,则过滤数组并分配过滤后的数组

const-map=newmap([[123'、[[foo'、[bar']]、[456'、[baz'、[qux']、[qux'、[corge']]);
映射forEach((v,k,m)=>{
如果(v.some(a=>a[0]='qux')){
m、 设置(k,v.filter(a=>a[0]!='qux');
}
});

log([…map])您可以使用for of循环动态执行键,如下所示:

顺便说一句,打开devtools签出新映射,因为映射无法正确显示在代码段中

const Map=new Map().set('123'[
['foo','bar']
]).set('456'[
['baz','qux'],
['quox','corge']
]);
对于(让el的地图){
Map.set(el[0],(Map.get(el[0])).filter(array=>array[0]!==quox');
}

控制台日志(Map)迭代映射的键值对,该值将具有外部数组,我们可以从中筛选出具有我们要查找的值的内部数组。我们可以从forEach函数中获得内部数组的索引,使用它我们可以使用splice函数从外部数组中删除内部数组

const map = new Map().set('123', [ [ 'foo', 'bar' ] ]).set('456', [ [ 'baz', 'qux' ], [ 'quux', 'corge' ] ]);
map.forEach((v, k)=>
{
     v.forEach((arr, idx)=> {
     if(arr.includes('quux')){
            v.splice(idx,1);
        }
    },)
});
console.log(map);

不确定从性能角度来看,始终使用
Array.prototype.filter
或在过滤数组之前使用
Array.prototype.some
是否更好

此解决方案只过滤所有阵列,而不检查“quux”的外观

const map = new Map().set('123', [ ['foo', 'bar' ] ]).set('456', [ [ 'baz', 'qux' ], [ 'quux', 'corge' ] ]);

map.forEach((val, key) => {
  val = val.filter(arr => arr[0] !== 'quux');
  map.set(key, val);
});

console.log(map);

使用循环。您还应该了解数组函数,如
forEach()
map()
filter()
、和
reduce()
。使用
map
而不是对象有什么原因吗?@code学徒我正在使用一个使用映射的库,因此我别无选择,只能使用映射方法来处理它。这就是
[…map]
技巧很巧妙,也将其整合到了我的答案中。今天学到了新东西!