亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

我如何通過比較 ReactJs 中的另一個數組來呈現數組值

我如何通過比較 ReactJs 中的另一個數組來呈現數組值

嚕嚕噠 2023-05-11 10:13:35
我有一些來自道具的數組,如下所示this.props.fruits= [  {    source: "Apple",    code: 101,  },  {    source: "banana",    code: 105,  },  { source: "Mango",    code: 107,  },];在我的狀態下,我必須僅保存代碼以將其發送到后端我的狀態如下所示this.state ={   myfruits:[101,105]}我必須在渲染 DOM 元素的 DOM 元素示例中渲染 myfruits 名稱My Fruits : Apple , banana
查看完整描述

2 回答

?
Cats萌萌

TA貢獻1805條經驗 獲得超9個贊

您可以結合使用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()}`);


查看完整回答
反對 回復 2023-05-11
?
眼眸繁星

TA貢獻1873條經驗 獲得超9個贊

您可以結合使用 filter 和 map 方法,

this.props.fruits.filter((fruit)?=>?this.state.myfruits.includes(fruit.code))
??????????.map((fruit)?=>?fruit.source)
查看完整回答
反對 回復 2023-05-11
  • 2 回答
  • 0 關注
  • 159 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號