我需要些帮助。
我有两个数组,我必须检查第一个数组是否有来自React中另一个对象数组的所有ID值,然后只返回"True“或"False”。第一个数组如下所示:
this.state = { firstArray: ["1"] }
第二个数组如下所示:
this.state = { secondArray: [ {id:1, name: Joe}, {id:2, name: Bill}, {id:3, name: Jason}]
我试过这样的东西
compareTwoArrays = () => {
this.state.firstArray.includes(x => x === this.state.secondArray.map(item => item.id)
)}
有没有办法让它只返回"True“或"False”呢?
提前谢谢。:)
发布于 2020-07-09 23:36:11
您应该组合使用every
和includes
函数,如下所示:
const firstArray = ["1"]
const secondArray = [ {id:1, name: Joe}, {id:2, name: Bill}, {id:3, name: Jason}]
const condition = firstArray.every(id => secondArray.includes(obj => obj.id === id))
这将测试第一个数组中的每个项在第二个数组中都有一个相应的对象。
编辑:如果你需要做的是另一种方式,那么解决方案是
const firstArray = ["1"]
const secondArray = [ {id:1, name: Joe}, {id:2, name: Bill}, {id:3, name: Jason}]
const condition = secondArray.every(obj => firstArray.includes(id => obj.id === id))
https://stackoverflow.com/questions/62818480
复制相似问题