Home > OS >  Flutter convert array format
Flutter convert array format

Time:06-08

How to convert this below array:

[{timeNameID: [2, 4, 5, 6, 7, 8], alarmIDAdzan: [4, 5, 5, 5, 5, 5], alarmIDIqamah: [5, 5, 4, 4, 4, 4]}]

to be:

[
  { timeNameID: '2', alarmIDAdzan: '4', alarmIDIqamah: '5' },
  { timeNameID: '4', alarmIDAdzan: '5', alarmIDIqamah: '5' },
  { timeNameID: '5', alarmIDAdzan: '5', alarmIDIqamah: '4' },
  { timeNameID: '6', alarmIDAdzan: '5', alarmIDIqamah: '4' },
  { timeNameID: '7', alarmIDAdzan: '5', alarmIDIqamah: '4' },
  { timeNameID: '8', alarmIDAdzan: '5', alarmIDIqamah: '4' }
]

Here is my code so far:

var makeArray = [
  {
    'timeNameID': selectedTimeNameID,
    'alarmIDAdzan': selectedAlarmAdzanID,
    'alarmIDIqamah': selectedAlarmIqamahID
  }
];

Is there any way to do the convert?

CodePudding user response:

You could try this

  var a = [{"timeNameID": [2, 4, 5, 6, 7, 8], "alarmIDAdzan": [4, 5, 5, 5, 5, 5], "alarmIDIqamah": [5, 5, 4, 4, 4, 4]}];
  var b = Iterable<int>.generate(a[0]["timeNameID"]!.length).map((e) =>
      {"timeNameID":a[0]["timeNameID"]![e],"alarmIDAdzan":a[0]["alarmIDAdzan"]![e],"alarmIDIqamah":a[0]["alarmIDIqamah"]![e]});
  print(b);

this prints

({timeNameID: 2, alarmIDAdzan: 4, alarmIDIqamah: 5}, {timeNameID: 4, alarmIDAdzan: 5, alarmIDIqamah: 5}, {timeNameID: 5, alarmIDAdzan: 5, alarmIDIqamah: 4}, ..., {timeNameID: 7, alarmIDAdzan: 5, alarmIDIqamah: 4}, {timeNameID: 8, alarmIDAdzan: 5, alarmIDIqamah: 4})

Note thought, that this requires the fields to exist and all be the same length. It will lead to errors if it's not the case

  • Related