基于另一个数组的嵌套过滤器数组

时间:2019-12-13 02:44:17

标签: javascript arrays filter nested

我想过滤第二个数组cards,以便它仅显示在groups.cardsFilter数组中第一个对象(id = 1)中的cardsfFilter数组中指定的记录

数组和所需的结果低于

const groups = [
  {
    id: 1,
    name: 'Melbourne Bands',
//Below is the array that I need to act as the filter for the cards array
    cardsFilter: [1, 2]
  },
  {
    id: 2,
    name: 'Sydney Bands',
    cardsFilter: [3]
  }
]

const cards =  [
  {
    id: '1',
    url: 'jimmyyukka.com',
    name: 'Jimmy Yukka',
    CreatedByUserId: 1
  },
  {
    id: '2',
    url: 'jimmyyukka.com',
    name: 'Due North',
    CreatedByUserId: 1
  },
  {
    id: '3',
    url: 'jimmyyukka.com',
    name: 'INXS',
    CreatedByUserId: 1
  }
]


const desiredResult = [
  {
    id: '1',
    url: 'jimmyyukka.com',
    name: 'Jimmy Yukka',
    CreatedByUserId: 1
  },
  {
    id: '2',
    url: 'jimmyyukka.com',
    name: 'Due North',
    CreatedByUserId: 1
  },
]

我正在努力解决这个问题,并且对于这种简单的方法,找不到堆栈溢出的示例。

我已经尝试过(一项记录) 我不知道如何使用数组

const notQuiteRight= cards.filter(function(getFile){
  return getFile.id === "1"
});

1 个答案:

答案 0 :(得分:3)

cardsFilter数组的第一个对象中提取属性groups,然后对cards数组使用过滤器。

const groups = [{
    id: 1,
    name: 'Melbourne Bands',
    //Below is the array that I need to act as the filter for the cards array
    cardsFilter: [1, 2]
  },
  {
    id: 2,
    name: 'Sydney Bands',
    cardsFilter: [3]
  }
]

const cards = [{
    id: '1',
    url: 'jimmyyukka.com',
    name: 'Jimmy Yukka',
    CreatedByUserId: 1
  },
  {
    id: '2',
    url: 'jimmyyukka.com',
    name: 'Due North',
    CreatedByUserId: 1
  },
  {
    id: '3',
    url: 'jimmyyukka.com',
    name: 'INXS',
    CreatedByUserId: 1
  }
]


const { cardsFilter } = groups[0];

const desiredOutput = cards.filter(({id}) => cardsFilter.includes(+id));

console.log(desiredOutput);