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



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

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,然后找到相应的键,然后删除该项。Map中的键和值将是动态的(但结构将是相同的(,而要搜索的元素将是静态的,即:"quux",我的意思是Map中的内容可能会有所不同,我只是执行搜索和删除。

您可以迭代映射,如果找到所需的值,则过滤数组并分配过滤后的数组。

const map = new Map([['123', [['foo', 'bar']]], ['456', [['baz', 'qux'], ['quux', 'corge']]]]);
map.forEach((v, k, m) => {
if (v.some(a => a[0] === 'quux')) {
m.set(k, v.filter(a => a[0] !== 'quux'));
}
});
console.log([...map]);

您可以循环遍历Map的值,对每个值v使用findIndex来查看它是否包括第一个元素为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的值ping到我们不想要的数组中的filter来创建一个新映射:

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

您可以使用for-of循环动态执行密钥,如下所示:

BTW打开您的devtools来签出新地图,因为地图无法正确显示在代码片段中。

const Map = new Map().set('123', [
['foo', 'bar']
]).set('456', [
['baz', 'qux'],
['quux', 'corge']
]);
for (let el of Map) {
Map.set(el[0], (Map.get(el[0])).filter(array => array[0] !== 'quux'));
}
console.log(Map);

我希望这是你想要的,否则你可以发表评论,我会看一看;(。

在映射的键值对上迭代,值将具有外部数组,我们可以从中筛选出具有我们要查找的值的内部数组。我们可以从forEach函数中获得内部数组的索引,使用该函数可以使用拼接函数从外部数组中删除内部数组。

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);

最新更新