Skip to content
Advertisement

Diferent ways to rearrange data from one array into another

From API, I get array of attendances by date with members data. My task is to convert that data to array of objects with clients data end attend_date. I managed to accomplish that in following snippet. My plea to You is for hint for other, perhaps more performant or more elegant way for solving my task.

const attendances = [
  { _id: '1',
    attend_date: '2020-12-31',
    members: [{_id: '1', client: '1', present: true}, {_id: '2', client: '2', present: true}, {_id: '3', client: '3', present: true}]
  },
  {_id: '2',
    attend_date: '2021-01-01',
    members: [{_id: '1', client: '1', present: true}, {_id: '2', client: '2', present: true}, {_id: '3', client: '3', present: true}]
  },
  {_id: '3',
    attend_date: '2021-01-04',
    members: [{_id: '1', client: '1', present: true}, {_id: '2', client: '2', present: true}, {_id: '3', client: '3', present: true}]
  }
]

const mapAttendances = () => {
  let obj,
    arr = [];
  for (let i = 0; i < attendances.length; i++) {
    for (let j = 0; j < attendances[i].members.length; j++) {
      obj = {
        date: attendances[i].attend_date,
        present: attendances[i].members[j].present,
        client: attendances[i].members[j].client,
      };
      arr.push(obj);
    }
  }
  return arr;
}
console.log(mapAttendances())

Advertisement

Answer

You can also do this with some nested maps and a little destructuring

const attendances = [
  { _id: '1',
    attend_date: '2020-12-31',
    members: [{_id: '1', client: '1', present: true}, {_id: '2', client: '2', present: true}, {_id: '3', client: '3', present: true}]
  },
  {_id: '2',
    attend_date: '2021-01-01',
    members: [{_id: '1', client: '1', present: true}, {_id: '2', client: '2', present: true}, {_id: '3', client: '3', present: true}]
  },
  {_id: '3',
    attend_date: '2021-01-04',
    members: [{_id: '1', client: '1', present: true}, {_id: '2', client: '2', present: true}, {_id: '3', client: '3', present: true}]
  }
]

const mapAttendances = () => {
  return attendances.flatMap(({attend_date:date, members}) => {
     return  members.map(({_id,...r}) => ({ date,...r }));  
  });
}

console.log(mapAttendances())
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement