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;
})
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With