Wildcard Search in a collection with lodash

倖福魔咒の 提交于 2019-12-10 18:14:40

问题


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.

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

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

回答1:


You can do the same with a function passed to _.find, like this

_.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.



来源:https://stackoverflow.com/questions/41368469/wildcard-search-in-a-collection-with-lodash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!