I have certain array from props which is given below
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
My Fruits : Apple , banana
You could make a combination of filter , map and join to get this working.
Example is not React but shows you how this can be achieved.
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,
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 .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.