【问题标题】:lodash search text in object arraylodash 在对象数组中搜索文本
【发布时间】:2021-04-04 05:44:48
【问题描述】:

在我的 Angular 应用中,我有搜索输入

 <input
    id="search"
    type="text"
    placeholder="search"
    class="form-control"
    formControlName="search"
    (keydown)="mySearch()"
  >

功能是:

mySearch() {
  // search code here
}

这是我需要搜索的数组

[
{
    "_id": "1",
    "productName": "test name 1",
    "article": "11111",
},
{
    "_id": "2",
    "productName": "test name 2",
    "article": "11111",
},
{
    "_id": "3",
    "productName": "test name 3",
    "article": "4",
},
{
    "_id": "4",
    "productName": "test name 4",
    "article": "11111",
},
{
    "_id": "5",
    "productName": "test name 5",
    "article": "111111",
},
{
    "_id": "6",
    "productName": "test name 6",
    "article": "11111111",
},
{
    "_id": "7",
    "productName": "test name 7",
    "article": "4d",
}
]

当我输入“4”作为结果时,我需要在 productName 和 article 中包含字符串“4”的所有对象.. 像这样:

[
{
    "_id": "3",
    "productName": "test name 3",
    "article": "4",
},
{
    "_id": "4",
    "productName": "test name 4",
    "article": "11111",
},

{
    "_id": "7",
    "productName": "test name 7",
    "article": "4d",
}
]

我如何使用 lodash 做到这一点?我需要搜索 IN 并在对象中的 2 个字段中搜索。谢谢;)

【问题讨论】:

  • 我猜你不需要 lodash,尝试使用过滤器,例如:articleArray.filter(obj => obj.productName.includes("4") || obj.article .includes("4"))

标签: javascript angular lodash


【解决方案1】:

您可以使用此代码:

array.filter(a=> _.values(a).some(b => b.includes("4")));

_.values 是一个 lodash 方法

【讨论】:

  • 嘿,阿利克斯。非常感谢,但我收到错误 core.js:4352 ERROR TypeError: b.includes is not a function
  • 因为我应该将对象中所有值存储的类型都是字符串。如果你使用其他类型,你必须使用自己的方法来比较
  • 再次非常感谢您!我将创建仅包含字符串类型的数组,然后使用您的代码。谢谢!!!!!!
猜你喜欢
  • 1970-01-01
  • 2015-10-23
  • 1970-01-01
  • 2018-03-13
  • 2017-12-10
  • 2021-10-02
  • 2017-05-21
  • 2011-04-07
  • 2015-09-12
相关资源
最近更新 更多