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

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

我有一些来自道具的数组,如下所示

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

您可以结合使用过滤器和映射方法,

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

这应该可以解决您的问题。您可以阅读有关地图和过滤器的更多信息 here.

您可以组合 filter, map and 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()}`);