Pratap Penmetsa
Pratap Penmetsa

Reputation: 1237

How to convert API data to section list data in react-native using javascript

I want to convert API data to section list formate in react-native. So that I can display my data in the section list. Below is my API data

  data:[
    {
      id:'1',
      fullname: "seela",
      inspection_date: "2020-06-10T04:45:32Z",
      issues: 1,
      response:{
        shift_name:'Day'
      }
    },
    {
      id:'2',
      fullname: "Raju vijayan",
      inspection_date: "2020-06-9T04:45:32Z",
      issues: 3,
      response:{
        shift_name:'Afternoon'
      }
    },
    {
      id:'3',
      fullname: "Pratap P",
      inspection_date: "2020-06-8T04:45:32Z",
      issues: 2,
      response:{
        shift_name:'Afternoon'
      }
    }
  ]

I want to convert to the section list formate as below.

data:[
  {
    shift_name:'Day',
    data:[
    {
      id:'1',
      fullname: "seela",
      inspection_date: "2020-06-10T04:45:32Z",
      issues: 1,
      response:{
        shift_name:'Day'
      }
     }
    ]
  },
  {
    shift_name:'Afternoon',
    data:[
      {
        id:'2',
        fullname: "Raju vijayan",
        inspection_date: "2020-06-9T04:45:32Z",
        issues: 3,
        response:{
          shift_name:'Afternoon'
        }
      },
      {
        id:'3',
        fullname: "Pratap P",
        inspection_date: "2020-06-8T04:45:32Z",
        issues: 2,
        response:{
          shift_name:'Afternoon'
        }
      }
    ]
  }
]

How can I convert API data to section list in react-native with array.map or any other operator

Upvotes: 1

Views: 863

Answers (1)

Guruparan Giritharan
Guruparan Giritharan

Reputation: 16364

You can use a reducer function like below.

const data = [{
    id: '1',
    fullname: "seela",
    inspection_date: "2020-06-10T04:45:32Z",
    issues: 1,
    response: {
      shift_name: 'Day'
    }
  },
  {
    id: '2',
    fullname: "Raju vijayan",
    inspection_date: "2020-06-9T04:45:32Z",
    issues: 3,
    response: {
      shift_name: 'Afternoon'
    }
  },
  {
    id: '3',
    fullname: "Pratap P",
    inspection_date: "2020-06-8T04:45:32Z",
    issues: 2,
    response: {
      shift_name: 'Afternoon'
    }
  }
];

const reducer = (acc, cur) => {
  const item = acc.find((x) => x.shift_name === cur.response.shift_name);
  if (item) {
    item.data.push(cur);
  } else {
    acc.push({
      shift_name: cur.response.shift_name,
      data: [cur]
    });
  }
  return acc;
};

console.log(data.reduce(reducer, []))

Upvotes: 2

Related Questions