Yashvardhan Khaitan
Yashvardhan Khaitan

Reputation: 143

Search and select JSON for particular objects based on array of values

I am trying to select multiple objects from a JSON file based on an array of values. To explain it further, I have an array var list = ['test1', 'test2']; and I have a variable that has the following contents:

var data = [
     {
        "unitid": 177834,
        "name": "Test65",
        "year": 2019,
        "HD2019_city": "Kirksville",
     },
     {
        "unitid": 491464,
        "name": "Test77",
        "year": 2019,
        "HD2019_city": "Cerritos",
     },
     {
        "unitid": 459523,
        "name": "Test95",
        "year": 2019,
        "HD2019_city": "Richardson",
     },
     {
        "unitid": 485500,
        "name": "Test1",
        "year": 2019,
        "HD2019_city": "Inglewood",
     },
     {
        "unitid": 134811,
        "name": "Test2",
        "year": 2019,
        "HD2019_city": "Miami",
     }
    ];

I want to retrieve:

    {
        "unitid": 485500,
        "name": "Test1",
        "year": 2019,
        "HD2019_city": "Inglewood",
     },
     {
        "unitid": 134811,
        "name": "Test2",
        "year": 2019,
        "HD2019_city": "Miami",
     }

Then using that result I want to display it to the user with the rest of the key-value pairs.

Upvotes: 1

Views: 1281

Answers (1)

Joel Durham
Joel Durham

Reputation: 36

data.filter(item => list.includes(item.name.toLowerCase()))

Upvotes: 1

Related Questions