正则表达式通过对象数组

时间:2015-10-26 14:08:16

标签: javascript arrays regex

我有一个大约有1000个元素的数组,例如:

var peoples = [
  { "name": "bob", "dinner": "pizza" },
  { "name": "john", "dinner": "sushi" },
  { "name": "larry", "dinner": "hummus" },
  { "name": "jacob", "dinner": "pizza" }
............];

我想用正则表达式搜索数组的"dinner" s元素,因此它不一定是确切的类型。例如,假设输入为"piz";然后它应该将所有匹配的元素作为数组返回。在上面的示例中,它应该返回:

var result = [{ "name": "bob", "dinner": "pizza" },
{ "name": "jacob", "dinner": "pizza" }]

我知道如何使用javascript中的.match函数搜索字符串,但我不知道如何在数组中使用类似的函数。我怎么能这样做?

1 个答案:

答案 0 :(得分:2)

您可以将.filterdynamic RegExp一起使用,就像这样

var search = "piz";
var condition = new RegExp(search);

var peoples = [
  { "name": "bob", "dinner": "pizza" },
  { "name": "john", "dinner": "sushi" },
  { "name": "larry", "dinner": "hummus" },
  { "name": "jacob", "dinner": "pizza" }
];

var result = peoples.filter(function (el) {
  return condition.test(el.dinner);
});

console.log(result);