Having problem to desctructure my data on React

89 views Asked by At

The upcomingWork contains my apis data. What I want here is to insert this as an array to display it on my calendar, below are the example of structured data I want.

Actually, the upcomingWork contains a lot of attributes but I just want to get those three attributes to display on my calendar.

const data = upcomingWork.map(u => u.id && u.title && u.created_at);

Example of array that I want to create from data.

  const events = [
    {
      id: 1,
      title: 'My event',
      start: new Date(2020, 4, 8, 10, 0),
      end: new Date(2020, 4, 8, 14, 0),
    },
  ];
4

There are 4 answers

2
Batzz On BEST ANSWER

The map that you have will simply set every value to either true if all values are truey or false if any of them are falsey. if you want to extract those 3 values just change the map to this:

const data = upcomingWork.map(({id, title, created_at}) => ({id, title, created_at}))
0
Abhishek Shastri On

Whatever you returned is not going to give you any desired data. I think you misunderstood the map method of Array.

Instead you should use map like:

const data = upcomingWork.map(u => {
             const {id, title, created_at} = u;
                 return {
                   id,
                   title,
                   created_at
                 }
              });
0
Majid Eltayeb On
const data = upcomingWork.map(u => {
    return { id: u.id, title: u.title };
});
0
Adam Jeliński On

Your upcomingWork.map doesn't create an object at all, so it has no chance of creating the expected data. Instead, you can map appropriate properties of the u object to the new keys in a new object you create.

const events = upcomingWork.map(u => ({
    id: u.id,
    title: u.title,
    start: u.created_at,
    end: u.end    //change the u.end to whatever property you have in your data
}));

(the new object has to be wrapped in () to ensure JS interprets it as a value, not a function body)