0

Consider the code below:

  componentDidMount(){
    const id = localStorage.getItem('id');



     fetch(`http://localhost:9000/api/calendar/list/${id}`,)
     .then((resp)=>{
       resp.json().then((res)=>{
          this.setState({
            data: res.data.map(item => {
              return {
                title: item.title,
                startDate: new Date(item.startDate),
                endDate: new Date(item.endDate),
                eventId: item.eventType  // from api it provide on string but I need to convert it in to an integer
              };

            })
          });
       })
     })

   }

The result from the API are here:

enter image description here

So on the frontend js, I need to set the eventId to a number like Conference in num 1, Launching in num 2, Trade Shows in num 3. Is it any way I can do it ?

2 Answers 2

2

You can create an object to map the string to a number like this, where item1 and item2 are examples of what your API data could be:

const item1 = {
  userId: 1,
  startDate: 123456,
  endDate: 123456,
  eventType: 'Conference'
};
const item2 = {
  userId: 2,
  startDate: 123456,
  endDate: 123456,
  eventType: 'Launching'
};

const map = { Conference: 1, Launching: 2, Trade: 3 };

console.log(map[item1.eventType]); // eventId will be 1 for Conference
console.log(map[item2.eventType]); // eventId will be 2 for Launching

In your code this would be

const map = { Conference: 1, Launching: 2, Trade: 3 };
fetch(`http://localhost:9000/api/calendar/list/${id}`,)
     .then((resp)=>{
       resp.json().then((res)=>{
          this.setState({
            data: res.data.map(item => {
              return {
                title: item.title,
                startDate: new Date(item.startDate),
                endDate: new Date(item.endDate),
                eventId: map[item.eventType]
              };
            })
          });
       })
     })
Sign up to request clarification or add additional context in comments.

1 Comment

@kokoka no problem
0

You can leverage Switch Case if you know all the values

getEventId = eventType => {
  switch (eventType){
    case 'Conference'
      return 1;

      ...... // rest of the cases

     }
   }
}

Then use this function to map eventType to eventId

eventId: getEventId(item.eventType)

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.