0

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.

Ori Drori
  • 183,571
  • 29
  • 224
  • 209
Billy Keef
  • 31
  • 1
  • 7
  • 1
    Does this answer your question? [For..In loops in JavaScript - key value pairs](https://stackoverflow.com/questions/7241878/for-in-loops-in-javascript-key-value-pairs) And then: https://stackoverflow.com/questions/1789945/how-to-check-whether-a-string-contains-a-substring-in-javascript – Justinas Jan 22 '21 at 15:14

3 Answers3

1

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)

Since Map.keys() returns an iterator, you can use for...of to go over it lazily (no need to create an array of keys):

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)
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
0

You can use this:

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");
Ali Esmailpor
  • 1,209
  • 3
  • 11
  • 22
0

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'))
Wimanicesir
  • 4,606
  • 2
  • 11
  • 30