Sudharsan Venkatraj
Sudharsan Venkatraj

Reputation: 581

How to match a key in an object with a given string?

I am trying to match a key in an object with string. It works fine if an object contains single key but if it contains many keys it fails to match.can anyone help me with this?

object

let object = {
    user_name: "sample",
    user_email: "[email protected]"
}

trying to match with given string

for (let key in dict) {
    var res = key.match(/email/g)[0];
    console.log(res)
}

expected output

user_email

Upvotes: 1

Views: 1917

Answers (4)

Imtiyaz Shaikh
Imtiyaz Shaikh

Reputation: 625

Do you mean like this?

let object = {
  user_name: "sample",
  user_email: "[email protected]"
}

let variable = 'email'  // New edit as per first comment

Object.keys(object).forEach(element => {
  if (element.includes(variable)) {
    console.log(element)
    console.log(object[element])
  }
})

Upvotes: 2

Sami Ahmed Siddiqui
Sami Ahmed Siddiqui

Reputation: 2386

How about this:

let dict = {
    user_name: "sample",
    user_email: "[email protected]"
}

var check;
var res;
for (let key in dict) {
    check = "";
    check = key.match(/email/g);
    if (check) {
        // return the matched element like "email" only
        // res = check;
        // return the element which contains "email" in "key"
        res = key;
    }
}
console.log(res);

Just change key.match(/email/g)[0]; with key.match(/email/g); and it works just fine. You don't need to define [0].

Upvotes: 2

arizafar
arizafar

Reputation: 3122

If you are expecting multiple keys which matches the required patter you can map through and filter

Use String.prototype.includes when not looking for pattern matches

let object = {
	user_name: "sample",
	user_email: "[email protected]",
        user_secondary_email: "[email protected]"
}

let output = Object.keys(object).filter(key => key.includes('email'));
console.log(output)

Upvotes: 2

Haytam
Haytam

Reputation: 4733

You should check if the match is successfull:

let dict = {
    user_name: "sample",
    user_email: "[email protected]"
}

for (let key in dict) {
    var res = key.match(/email/g);
    if (res) { // match
        console.log(dict[key])
    }
}

Upvotes: 1

Related Questions