Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript/Jquery regex for matched key and return its Value

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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])
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading