0

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

2 Answers 2

2

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()}`);

Sign up to request clarification or add additional context in comments.

2 Comments

.join(", ") method is not working while rendering it returns as [object,object].. is there any solution
@Sanjaikumar It means the items you join are objects. You only need to return the name that you want to show, if you have some more code i can try to debug it.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.