简体   繁体   English

如何根据值对象的属性从地图中删除元素

[英]How to delete element from a Map based on property of value object

myMap.set(id, {x: 10, y: 20})
myMap.delete(id)

How can I delete element from a Map based on property of value object? 如何根据值对象的属性从Map中删除元素? for example in above code instead of deleting based on key, delete based on x from value 例如在上面的代码中,而不是基于键删除,而是基于x从值中删除

You'll have to iterate over the map's entries and find the one with the value you want, then delete the associated key from the map: 您必须遍历地图的entries并找到具有所需值的entries ,然后从地图中删除关联的键:

 const map = new Map(); const id = 'foo'; map.set(id, {x: 10, y: 20}); console.log(map.size); const foundIdEntry = [...map.entries()] .find(([, { x }]) => x === 10); if (foundIdEntry) map.delete(foundIdEntry[0]); console.log(map.size); 

That said, if you're having to do something like this regularly, it would probably be a lot better to reconsider your data structure - you might want a Map whose keys are the x values, rather than whose keys are the IDs: 也就是说,如果您必须定期执行此类操作,那么重新考虑数据结构可能会好得多-您可能想要一个Map其键为x值,而不是其键为ID:

map.set(10, { id: 'foo', y: 20 });

Or, when setting a value to the map, also set a key-value pair in a separate object that maps x s to its associated id , so that you can access it in the future with plain property lookup, rather than .find : 或者,在为地图设置值时,还要在一个单独的对象中设置一个键-值对,该对象将x s映射到其关联的id ,以便将来可以使用普通属性查找而不是.find来访问它:

const idsByX = {};
map.set(id, {x: 10, y: 20});
idsByX['10'] = id;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM