[Fixed] lodash search text in object arrray

Issue

In my angular app I have search input

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

function is:

mySearch() {
  // search code here
}

This is array where I need to search

[
{
    "_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",
}
]

when I type "4" as result I need to have all object where string include "4" in productName and article.. like this:

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

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

How I can do that using lodash? I need something like search IN and search in 2 fields in object. Thanks 😉

Solution

you can use this code:

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

_.values is a lodash method

Leave a Reply

(*) Required, Your email will not be published