Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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;
})
like image 978
Ajay Srikanth Avatar asked Oct 29 '22 14:10

Ajay Srikanth


1 Answers

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.

like image 143
thefourtheye Avatar answered Nov 10 '22 20:11

thefourtheye