简体   繁体   English

通过其属性值在 Map 中查找元素

[英]Find element in Map by it's property value

I have a Map of objects:我有一个对象地图:

const myMap = new Map() 

myMap.set(123, {
  name: 'Lorem',
  elements: {
    books: ['book#1', 'book#2', 'book#3']
  }
})

myMap.set(521, {
  name: 'Ipsum',
  elements: {
    books: ['book#42', 'book#13', 'book#42']
 }
})

And at some point, I will need to find an element in Map, which contain book#42 in elements.books array.在某些时候,我需要在 Map 中找到一个元素,它在elements.books数组中包含book#42 How Can I do it properly?我怎样才能正确地做到这一点?

You can loop through the Map() with the for...of statement.您可以使用for...of语句循环遍历Map() This statement exposes each entry, which is a key-value pair.此语句公开每个条目,这是一个键值对。 The value is where you should check for your book.价值是你应该检查你的书的地方。 Specifically in the elements.books array.特别是在elements.books数组中。 When you found your book, return the key of the entry.当你找到你的书时,归还条目的key Now you have the key to select the correct entry from the Map() .现在您有了从Map()选择正确条目的密钥。

 const myMap = new Map() myMap.set(123, { name: 'Lorem', elements: { books: ['book#1', 'book#2', 'book#3'] } }); myMap.set(521, { name: 'Ipsum', elements: { books: ['book#42', 'book#13', 'book#42'] } }); const findKeyOfBook = (book, map) => { let result = null; for (const [key, value] of map) { if (value.elements.books.includes(book)) { result = key; } } return result; }; const key = findKeyOfBook('book#42', myMap); const entryWithBook = myMap.get(key); console.log(entryWithBook);

You can do simply by doing this using entries :您可以简单地使用entries执行此操作:

 const myMap = new Map() myMap.set(123, { name: 'Lorem', elements: { books: ['book#1', 'book#2', 'book#3'] } }) myMap.set(521, { name: 'Ipsum', elements: { books: ['book#42', 'book#13', 'book#42'] } }) for([key,value] of myMap.entries()){ if(value.elements.books.includes('book#42')){ console.log("Found value",key,value) } }

You can convert the iterator returned by Map.prototype.values() into an actual array (with the spread ( ... ) syntax or Array.from() ) and then use Array.prototype.find()您可以将Map.prototype.values()返回的迭代器转换为实际数组(使用 spread ( ... ) 语法或Array.from() ),然后使用Array.prototype.find()

 const myMap = new Map() myMap.set(123, { name: 'Lorem', elements: { books: ['book#1', 'book#2', 'book#3'] } }) myMap.set(521, { name: 'Ipsum', elements: { books: ['book#42', 'book#13', 'book#42'] } }) const findWithSpread = function(map, book) { return [...map.values()].find(entry => entry.elements.books.includes(book)); //return Array.from(map.values()).find(...); } const element = findWithSpread(myMap, "book#42"); console.log(element);

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

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