首页 > 解决方案 > 使用 Reactjs 中的属性过滤两个数组

问题描述

我有两个数组,想用 reactjs 过滤另一个数组。我只想显示checked=true并且value第一个数组中的属性等于listname第二个数组中的属性。

谁能帮助提供示例代码来做到这一点?

第一个数组:

[
  {
    "listname": "Cash Deposit",
    "totalsuccess": "45"
  },
  {
    "listname": "Cash Withdrawl",
    "totalsuccess": "25"
  },
  {
    "listname": "Fund Transfer",
    "totalsuccess": "9"
  }
]

第二个数组:

[
      {
        "name": "txn",
        "value": "Cash Deposit",
        "checked": true
      },
      {
        "name": "txn",
        "value": "Cash Withdrawl",
        "checked": false
      }
    ]

标签: javascript

解决方案


你可以使用filterwithsome

const a = [
      {
        "name": "txn",
        "value": "Cash Deposit",
        "checked": true
      },
      {
        "name": "txn",
        "value": "Cash Withdrawl",
        "checked": false
      }
    ]

const b = [
  {
    "listname": "Cash Deposit",
    "totalsuccess": "45"
  },
  {
    "listname": "Cash Withdrawl",
    "totalsuccess": "25"
  },
  {
    "listname": "Fund Transfer",
    "totalsuccess": "9"
  }
]

const res = a.filter(obj => {
   if(obj.checked) {
      return b.some(item => item.listname === obj.value);
   }
   return false;
})
console.log(res);


推荐阅读