Lodash通过regExp匹配找到

问题描述 投票:0回答:1

是否有可能使用lodash,regexp找到对象数组?例如:

a=val+"@"
b="@"+val
_.find(obj.dbColumns,{attr:{data-db-name: ***CONTAINS a || CONTAINS b*** }})

提前致谢。

arrays regex object find lodash
1个回答
2
投票

您可以传递一个测试每个元素的函数。 documentation给出了这个例子:

var users = [
  { 'user': 'barney',  'age': 36, 'active': true },
  { 'user': 'fred',    'age': 40, 'active': false },
  { 'user': 'pebbles', 'age': 1,  'active': true }
];

_.find(users, function(o) { return o.age < 40; });

所以这样的事情可能就是你想要的:

_.find(obj.dbColumns, function(o) {
    return (new RegExp ([a,b].join('|'))).test( o.yourAttribute );
});

或者如果您只想要子字符串搜索,而不是正则表达式:

_.find(obj.dbColumns, function(o) {
    return
        o.yourAttribute.indexOf(a) >= 0 ||
        o.yourAttribute.indexOf(b) >= 0;
});
© www.soinside.com 2019 - 2024. All rights reserved.