Filter multiple values in object

风流意气都作罢 提交于 2021-02-04 21:12:33

问题


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...


回答1:


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)



回答2:


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.



来源:https://stackoverflow.com/questions/58451947/filter-multiple-values-in-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!