简体   繁体   English

使用lodash的集合中的通配符搜索

[英]Wildcard Search in a collection with lodash

I've an array like the one shown below and I want to do a wildcard search and retrieve the corresponding value. 我有一个如下所示的数组,我想做一个通配符搜索并检索相应的值。 This is not returning me any result, can someone help me if there is any better way to do this. 这不会给我任何结果,如果有更好的方法可以帮助我。 I'm using lodash utilities in my nodejs application. 我在我的nodejs应用程序中使用lodash实用程序。

var allmCar = [
  {
    "_id": ObjectId("5833527e25bf78ac0f4ca30e"),
    "type": "mCar",
    "value": "ABDC",
    "__v": 0
  },
  {
    "_id": ObjectId("5833527e25bf78ac0f4ca30e"),
    "type": "mCar",
    "value": "XYZ ABD",
    "__v": 0
  },
  {
    "_id": ObjectId("5833527e25bf78ac0f4ca30e"),
    "type": "mCar",
    "value": "FGHJ",
    "__v": 0
  }
]

_.find(allmCar, {
  value: {
    $regex: 'XYZ'
  }
})

I finally ended up using _.includes as below 我终于最终使用了_.includes如下

_.each(allmCar,function(car){
    if(_.includes('XYZ', car.value)===true)
    return car;
})

You can do the same with a function passed to _.find , like this 您可以对传递给_.find的函数执行相同的_.find ,就像这样

_.find(allmCar, function(mCar) {
  return /XYZ/.test(mCar.value);
});

Or with arrow functions, 或者使用箭头功能,

_.find(allmCar, (mCar) => /XYZ/.test(mCar.value));

This will apply the function passed to all the items of the collection and if an item returns true , that item will be returned. 这将应用传递给集合的所有项的函数,如果项返回true ,则返回该项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM