Considere el siguiente escenario
const searchString = 'Gen'; const myDict = { 'Genesis': 'You are the beginning', 'Joel': 'Joe is cool' // Many other key value pairs } Necesito obtener You are the beginning porque searchString( Gen ) es una subcadena de Genesis .
¿Cómo puedo lograr esto de forma optimizada en JS?
Podrías hacer algo como:
const searchString = 'Gen'; const myDict = { 'Genesis': 'You are the beginning', 'Joel': 'Joe is cool' // Many other key value pairs } for (let key in myDict){ if(key.includes(searchString)){ console.log(myDict[key]) // You are the beginning } }Podrías usar find()
const searchString = 'Gen'; const myDict = { 'Genesis': 'You are the beginning', 'Joel': 'Joe is cool' // Many other key value pairs } const result = Object.entries(myDict).find(([k]) => k.includes(searchString)); console.log(result[1]); const searchString = 'Gen'; const myDict = { 'Genesis': 'You are the beginning', 'Joel': 'Joe is cool' // Many other key value pairs } const result = Object.entries(myDict).find(([k]) => k.includes(searchString)); console.log(result[1]);