使用lodash在集合中进行通配符搜索 [英] Wildcard Search in a collection with lodash

查看:435
本文介绍了使用lodash在集合中进行通配符搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的数组,我想进行通配符搜索并检索相应的值.这并没有给我任何结果,如果有更好的方法可以帮助我.我在我的nodejs应用程序中使用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'
  }
})

我最终使用_.includes如下

I finally ended up using _.includes as below

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

推荐答案

您可以对传递给_.find的函数进行相同的操作

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

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

或带有箭头功能,

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

这会将传递给集合中所有项目的函数应用,并且如果某个项目返回true,则该项目将被返回.

This will apply the function passed to all the items of the collection and if an item returns true, that item will be returned.

这篇关于使用lodash在集合中进行通配符搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆