如何在Map中找到键,其中键包含某个值?



如果我有一个对象,其中对象的键是不同的href's,映射到一个对象…我怎么能返回一个键,其中href包含一个特定的字符串…

例如:

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

我希望能够做一些事情,我可以输入12345并返回www.hello.com/12345

展开Map的.key()迭代器以获得一个键数组(href),然后使用Array.find()查找包含该字符串的项。

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)

由于Map.keys()返回一个迭代器,您可以使用for...of惰性地遍历它(不需要创建键数组):

const fn = (hashMap, str) => {
for(const key of hashMap.keys()) {
if(key.includes(str)) return key;
}
}
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)

const hrefMap = {
'www.hello.com/12345': {value: 1, color: 'red'},
'www.hello.com/0000': {value: 2, color: 'blue'}
}
// Create an array of the keys, in this case the URL's
var strings = Object.keys(hrefMap);
// Function that accepts a string and gives back the possible urls
function returnUrl(search) {
return strings.filter(s => s.indexOf(search) > -1);
}
// Example function
console.log(returnUrl('12345'))
console.log(returnUrl('0000'))

你可以这样做:

const hrefMap = {
'www.hello.com/12345': {value: 1, color: 'red'},
'www.hello.com/0000': {value: 2, color: 'blue'}
}
function doFunc(s){
for (const property in hrefMap ) {
// console.log(property);
if (property.indexOf(s) !== -1){
console.log("that's it", property, ":", hrefMap[property]);
}
}
}
doFunc("12345");

最新更新