Reputation: 581
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
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
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
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
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