admin管理员组文章数量:1313305
I have an array that has around 1000 elements, for example:
var peoples = [
{ "name": "bob", "dinner": "pizza" },
{ "name": "john", "dinner": "sushi" },
{ "name": "larry", "dinner": "hummus" },
{ "name": "jacob", "dinner": "pizza" }
............];
I want to search the "dinner"
s element of the array with a regex, so it doesn't has to be the exact type. For example, let's say the input is "piz"
; it should then return all the matching elements as an array. In the example above, it should return:
var result = [{ "name": "bob", "dinner": "pizza" },
{ "name": "jacob", "dinner": "pizza" }]
I know how to search a string using the .match
function in javascript, but I don't know how to use a similar function in an array. How can I do this?
I have an array that has around 1000 elements, for example:
var peoples = [
{ "name": "bob", "dinner": "pizza" },
{ "name": "john", "dinner": "sushi" },
{ "name": "larry", "dinner": "hummus" },
{ "name": "jacob", "dinner": "pizza" }
............];
I want to search the "dinner"
s element of the array with a regex, so it doesn't has to be the exact type. For example, let's say the input is "piz"
; it should then return all the matching elements as an array. In the example above, it should return:
var result = [{ "name": "bob", "dinner": "pizza" },
{ "name": "jacob", "dinner": "pizza" }]
I know how to search a string using the .match
function in javascript, but I don't know how to use a similar function in an array. How can I do this?
- 2 You should know, this is not multidimensional array. This is array of objects. Only possible method is coding logic in a loop. Hope this helps. – Vinod Kumar Commented Oct 26, 2015 at 14:10
- Just for the clarity, it's "A string" not "A piece of string" :P (Unless you mean a part of a string, in which case I guess it's almost correct, if a little confusing and you'd want "A piece of a string") – DBS Commented Oct 26, 2015 at 14:14
- .. and is it search is a "contains" pattern instead or a format pattern?.. If the answer is a contains pattern then do not use regex. And how about you trying on your first – Dalorzo Commented Oct 26, 2015 at 14:18
1 Answer
Reset to default 9You can use .filter
with dynamic RegExp
, like this
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);
本文标签: javascriptRegex through array of objectsStack Overflow
版权声明:本文标题:javascript - Regex through array of objects - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741927733a2405388.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论