如何与对象匹配?

How to match with an object?

我正在尝试将 textObject.keys(obj.cars)[index]

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

我知道您可以将它用于字符串,但我如何将它用于对象?

预期结果:

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

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

然而这似乎不起作用。

根本不需要正则表达式

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

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

console.log(text,car)

但如果你必须

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)

你可以用这个

text = 'bmw'

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

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

// Will print 'ok'

如果您的目标是在文本中匹配对象中的任何键,则动态构建正则表达式:

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(", "));

您在找这样的东西吗?

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>