Home > Back-end >  Javascript find dictionary items whose key matches a substring in an optimized way
Javascript find dictionary items whose key matches a substring in an optimized way

Time:06-25

Consider the below scenario

const searchString = 'Gen';

const myDict = {
'Genesis': 'You are the beginning',
'Joel': 'Joe is cool'
 // Many other key value pairs
}

I need to get You are the beginning because searchString(Gen) is a substring of Genesis.

How can I achieve this in an optimized way in JS?

CodePudding user response:

You could do something like:

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
    }
}

CodePudding user response:

You could use 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]);

CodePudding user response:

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]);

  • Related