如何解决我如何通过比较ReactJs中的另一个数组来呈现Array值
我从道具中得到了一些数组,如下所示
this.props.fruits= [
{
source: "Apple",code: 101,},{
source: "banana",code: 105,{ source: "Mango",code: 107,];
在我的状态下,我只需要保存代码以将其发送给后端,我的状态在下面给出
this.state ={
myfruits:[101,105]
}
我必须在DOM元素中呈现myfruits名称 呈现DOM元素的示例
My Fruits : Apple,banana
解决方法
您可以结合使用filter,map和join来使此工作正常。
示例不是React,而是向您展示了如何实现。
const fruits = [
{
source: "Apple",code: 101,},{
source: "banana",code: 105,{ source: "Mango",code: 107,];
const state = [101,105];
const getFruitNames = () => fruits
.filter(({ code }) => state.includes(code)) // Get all fruit objects where the code is also in state
.map(({ source }) => source) // Only return the source (name)
.join(","); // Turn into a comma seperated string
console.log(`My Fruits: ${getFruitNames()}`);
,
您可以结合使用过滤器和映射方法,
this.props.fruits.filter((fruit) => this.state.myfruits.includes(fruit.code))
.map((fruit) => fruit.source)
这应该可以解决您的问题。您可以了解有关地图和过滤器here的更多信息。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。