【问题标题】:React Native - How do I find if one of the values in an array matches one of the values in the other array?React Native - 我如何找到一个数组中的一个值是否与另一个数组中的一个值匹配?
【发布时间】:2018-05-24 13:03:37
【问题描述】:

我已经找到并尝试了.includes 来帮助解决这个问题。但是.includes 没有按我的预期工作。它实际上确实找到了数组中的哪个值与另一个数组中的值匹配,但它只匹配相似值

result_postid 结果用逗号映射

[10,22,12,36,45,206]

item.id 结果用逗号映射

[5,13,28,136,400,538]

我试图弄清楚为什么某些值在应该很明显是 false 时却一直返回 true。然后我得出结论,.includes 实际上是从 result_postid 中获取 36 并将其与 item.id 中的 136 匹配。这就是我使用.includes 设置if 语句的方式:

{result_postid.includes(item.id) ?
 <Text>True</Text>
 :
 <Text>False</Text>
}

这是结果:

result_postid | item.id | Result

10 != 5,13,28,136,400,538: False
22 != 5,13,28,136,400,538: False
12 != 5,13,28,136,400,538: False
36 =  5,13,28,136,400,538: True <--- this should be false
45 != 5,13,28,136,400,538: False
206 != 5,13,28,136,400,538: False

是否有可能找到数组中的一个值是否与另一个数组中的一个值完全匹配?

这是我 map 之前的 result_postid 的样子:

render() {

const result_postid = this.state.data_one.map(function(val) {
 return val.postid;
}).join(',');
}

[{"spaceid":"16","postid":"10"},{"spaceid":"16","postid":"22"},{"spaceid":"16","postid":"12"},{"spaceid":"16","postid":"36"},{"spaceid":"16","postid":"45"},{"spaceid":"16","postid":"206"}]

【问题讨论】:

  • 所以,我不清楚您的 result_postid 是否是一个数组...但是您可以尝试使用 lodash 查找任何值。 lodash.com/docs/4.17.10#find
  • 你确定 result.postid 是一个数组吗? String 类也有一个名为 includes() 的方法。

标签: arrays reactjs if-statement react-native


【解决方案1】:

您可以使用.some.findIndex 来实现相同的效果

const postId = [10,22,12,36,45,206]
const itemId = [5,13,28,136,400,538]
const res = postId.some(id => itemId.findIndex(elem => elem === id) > -1);
console.log(res)

用于渲染目的

render() {
   const isPresent = result_postid.some(id => item_id.findIndex(elem => elem === id) > -1);
   return (
      <View>
          {isPresent? <Text>True</Text>:<Text>False</Text>}
      </View>
   )
}

【讨论】:

  • 非常感谢!我将如何在render() 的 if 和 else 语句中进行设置? @ShubhamKhatri
  • @LaneyWilliams 在回答中更新了它
  • 好的,因为我的item.id 在一个平面列表中,我做了这样的事情:
  • {result_postid.some(id =&gt; item.id.findIndex(elem =&gt; elem === id) &gt; -1) ? &lt;Text&gt;True&lt;/Text&gt;:&lt;Text&gt;False&lt;/Text&gt;} 我得到了这个错误:TypeError: undefined is not a function (evaluating 'result_postid.some')
  • 我需要把它放在 const 中吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-10
相关资源
最近更新 更多