Pierre
Pierre

Reputation: 59

Filter multiple values in object

I need to filter an object by multiple values.

Example of object:

items: [
{
url: "https://...",
id: "1693",
type: "ABC",
currencyCode: "SEK",
longName: "Abc",
name: "ABC",
micCode: "DEF",
listingDate: "2018-05-25T00:00:00+02:00",
subType: "STOCK",
  market: {
   id: "NOROTC"
},
}
.....

If I filter one value it's fine:

var market = data.filter(item => item.market.id === 'NOROTC');

But what I need to do is something like:

var market = data.filter(item => item.market.id === 'NOROTC' && item.market.id === 'NGM');

I found some similar posts here on stackoverflow but none of them seems to work in my case. Is there a smart way to do this? I tried _.filter() aswell but to no success...

Upvotes: 1

Views: 721

Answers (2)

Amit
Amit

Reputation: 1560

Please check the below example:

var items = [{
    name: 'Amit',
    id: 101
  },
  {
    name: 'Amit',
    id: 1011
  },
  {
    name: 'Arthit',
    id: 102
  },
  {
    name: 'Misty',
    id: 103
  },
]

var filteredData = items.filter(item => item.name == 'Amit' || item.name== 'Misty');

console.log(filteredData)

Upvotes: 2

Harun Yilmaz
Harun Yilmaz

Reputation: 8558

You can have an array of IDs you want to filter and use Array.includes() to filter array as following:

var items = [
  {market: {id: "NOROTC"}},
  {market: {id: "NGM"}},
  {market: {id: "foo"}},
  {market: {id: "bar"}},
]

var searchItems = ["NOROTC","NGM"]

var filteredData = items.filter(item => searchItems.includes(item.market.id))

console.log(filteredData)

Hope this helps.

Upvotes: 1

Related Questions