Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
134 views
in Technique[技术] by (71.8m points)

javascript - How to find a key in a Map, where the key contains a certain value?

So if I have an object where the keys of the object are different href's that map to an object... how can I be returned a the key where the href contains a certain string...

For example:

const hrefMap = new Map<string, any>({
'www.hello.com/12345': {value: 1, color: 'red'},
'www.hello.com/0000': {value: 2, color: 'blue'}
})

I want to be able to do something where I can input 12345 and be returned www.hello.com/12345.

question from:https://stackoverflow.com/questions/65847745/how-to-find-a-key-in-a-map-where-the-key-contains-a-certain-value

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Spread the Map's .key() iterator to get an array of keys (hrefs), and then use Array.find() to find an item that includes the string.

const fn = (hashMap, str) => [...hashMap.keys()].find(k => k.includes(str))

const hrefMap = new Map([["www.hello.com/12345",{"value":1,"color":"red"}],["www.hello.com/0000",{"value":2,"color":"blue"}]])

const result = fn(hrefMap, '12345')

console.log(result)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...