简体   繁体   English

我如何通过比较 ReactJs 中的另一个数组来呈现数组值

[英]How do i render the Array value by comparing another array in ReactJs

I have certain array from props which is given below我有一些来自 props 的数组,如下所示

this.props.fruits= [
  {
    source: "Apple",
    code: 101,
  },
  {
    source: "banana",
    code: 105,
  },
  { source: "Mango",
    code: 107,
  },
];

in my state I have to save the code only for send it for back-end my state is given below在我的状态下,我必须保存代码仅用于将其发送给后端我的状态如下

this.state ={
   myfruits:[101,105]
}

I have to render the myfruits name in the DOM element example rendering DOM element我必须在渲染 DOM 元素的 DOM 元素示例中渲染 myfruits 名称

My Fruits : Apple , banana

You could make a combination of filter , map and join to get this working.您可以组合使用filtermapjoin来实现这一点。

Example is not React but shows you how this can be achieved.示例不是 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()}`);

You can use a combination of filter and map method,您可以结合使用 filter 和 map 方法,

this.props.fruits.filter((fruit) => this.state.myfruits.includes(fruit.code))
          .map((fruit) => fruit.source)

This should solve your problem.这应该可以解决您的问题。 You can read more about map and filter here .您可以在此处阅读有关地图和过滤器的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM