首页 > 解决方案 > 根据来自另一个对象数组的多个值过滤对象数组

问题描述

我有一个对象数组,

c = [
  {
     name: 'abc',
     category: 'cat1',
     profitc: 'profit1',
     costc: 'cost1'
  },
  {
     name: 'xyz',
     category: '',
     profitc: 'profit1',
     costc: ''
  },
  {
     name: 'pqr',
     category: 'cat1',
     profitc: 'profit1',
     costc: ''
  }
]

现在我想根据另一个对象数组过滤数组,第二个对象数组是,

arr = [
 {
   type:'profitc'
   value: 'profit1',
 },
 {
   type:'category'
   value: 'cat1',
 }
]

现在 arr 显示在带有多个选择选项的下拉列表中,并且对象中键值的值显示给用户,即利润 1、cat1 等。因此,如果用户选择profit1and cat1,那么我需要过滤数组c,这样,输出看起来像这样。

c = [
  {
     name: 'abc',
     category: 'cat1',
     profitc: 'profit1',
     costc: 'cost1'
  },
  {
     name: 'pqr',
     category: 'cat1',
     profitc: 'profit1',
     costc: ''
  }
]

我试着这样做。

let result = c.filter(e => {
  let istruecat = true

//arr is chosen value from user.
  arr.forEach(element => {
    istruecat = e[element.type] == element.value;
  })
  return istruecat;
})

但是当我这样做时,我会从c数组中获取所有对象。我在这里做错了什么?有没有办法使用 lodash.

标签: javascriptarraysjsonobject

解决方案


-您istruecat仅根据arr. 您应该使用 reduce 来累积值:

let result = c.filter(e => arr.reduce((acc, element) => acc && e[element.type] === element.value, true))


推荐阅读