Entity_101
Entity_101

Reputation: 79

How to match with an object?

I'm trying to match text with Object.keys(obj.cars)[index]

if (text.match(/hello/gi)) {
  // Do something
}

I know you can use it with strings, but how do I use it with objects?

Expected result:

const obj = {
  name: ['Peter'],
  cars: {
    "bmw": 2,
    "audi": 3
  }
}

if (text.match(/Object.keys(obj.cars)[index]/gi)) {
  // Found match with bmw or audi
}

However this doesn't seem to work.

Upvotes: 0

Views: 134

Answers (4)

Sidorina
Sidorina

Reputation: 66

Are you looking for something like this?

const root = document.querySelector('#root');
const input = document.querySelector('#input');
const button = document.querySelector('#button');
button.addEventListener('click', match);

const obj = {
  name: ['Peter'],
  cars: {
    "bmw": 2,
    "audi": 3
  }
}

const cars = Object.keys(obj.cars);

const div = document.createElement('div');

function match() {
const text = input.value;
const matchIndex = cars.indexOf(text);

if (matchIndex !== -1) {
  div.textContent = `${text} is a match!`
} else {
  div.textContent = `${text} is not a match!`
}
}
root.appendChild(div);
<input id='input'>
<button id='button'>Submit</button>
<div id='root'></div>

Upvotes: 0

trincot
trincot

Reputation: 350715

If your aim is to match in the text any of the keys in your object, then build a regular expression dynamically:

const obj = {
  name: ['Peter'],
  cars: {
    "bmw": 2,
    "audi": 3
  }
}

const text = "This is my bmw and audi.";
const regex = new RegExp("\\b(?:" + Object.keys(obj.cars).join("|") + ")\\b", "gi");

let matches = text.match(regex);
if (matches) console.log("The text has: " + matches.join(", "));

Upvotes: 1

Welyweloo
Welyweloo

Reputation: 98

You can use this

text = 'bmw'

const obj = {
  name: ['Peter'],
  cars: {
    "bmw": 2,
    "audi": 3
  }
}

if(text in obj.cars){
  console.log('ok');
}

// Will print 'ok'

Upvotes: 0

mplungjan
mplungjan

Reputation: 178265

No need for regexp at all

const obj = {
  name: ['Peter'],
  cars: {
    "bmw": 2,
    "audi": 3
  }
}

const text = "bmw";
const car = obj.cars[text];

console.log(text,car)

But if you must

const obj = {
  name: ['Peter'],
  cars: {
    "bmw": 2,
    "audi": 3
  }
}

const text = "bmw";
const index = 0;
const re = new RegExp(Object.keys(obj.cars)[index],"gi")

const car = text.match(re)

console.log(text,car)

Upvotes: 0

Related Questions