Home > Blockchain >  Javascript/Jquery regex for matched key and return its Value
Javascript/Jquery regex for matched key and return its Value

Time:02-12

var t = {
"Word1, Word2 Word3":"Word1, Word2", 
"Word5, Word6":"Word6", "Word7":"Word7", 
"Word8, Word9 and Word10":"Word8 and Word10"
}

//has value after page load, its saved from a cookie
var z = "Word9 and Word10"

Requirement: I would like to pass the variable z and retrieve the matched value from the object t.

So in this case it should return "Word8 and Word10" so i could use that value to make API call etc. Any suggestions would be much appreciated.

CodePudding user response:

Depending on how you want to handle duplicates wasn't mentioned, this solution loops through all the object's keys and checks if the key value includes the z variable

const t = {
"Word1 Word2 Word3":"Word1 Word2", 
"Word5 Word6":"Word6", "Word7":"Word7", 
"Word8 Word9 and Word10":"Word8 and Word10"
}
const z = "Word9 and Word10"

for (const key of Object.keys(t)) {
    if (key.includes(z)) {
        console.log(t[key])
    }
}
  • Related