How do i use regex to match the first key in an object

How to i match the key in this object literal

var reg = {

"key":"This is my first key",
"key2":"This is my second key"}

console.log(`This is my regex : ${reg[/([a-z])\w+/]}`)

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.

markdown_Forums

You do not, at least not like that, you use regex for strings and strings only. It is not for anything else. One of the following is normally how you check for a key:

if (keyYouWant in yourObject) {
  // Do something with yourObject[keyYouWant]
}

if (yourObject.hasOwnProperty(keyYouWant) {
  // Do something with yourObject[keyYouWant]
}

if (Object.keys(yourObject).includes(keyYouWant)) {
  // Do something with yourObject[keyYouWant]
}

It is possible, you need to extract the keys, then check each one. They are strings, so you can use the array method find to look for the first one that matches, then if that returns a result, look up the match in the object

const key = Object.keys(yourObject).find(key => key.match(yourRegex));

if (key) {
  // Do something with yourObject[key]
}

This helped me so much thanks

1 Like