使用React.js中的属性过滤两个数组

时间:2018-10-30 07:46:03

标签: javascript

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

有人可以帮助提供示例代码吗?

Firstarray:

[
  {
    "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
      }
    ]

2 个答案:

答案 0 :(得分:2)

您可以将filtersome一起使用

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);

答案 1 :(得分:0)

这是我要解决的方法。

public class Authorisation{

    //Authorises inputted session key with current active session keys
    public Boolean authorise(String key)
    {
        for (int i = 0; i < Login.KEYS.length; i++)
        {
            if (key.equals(Login.KEYS[i]))
            {
                return true;
            }
        }
        return false;
    }
}

如果您不想手动实现这些循环,则可以使用firstArray.forEach( item => { secondArray.forEach( secondItem => { if(secondItem.checked && item.listname === secondItem.value) { //do your action here } }) }) 原型

希望它会有所帮助:)