Reputation: 187
I have a response from REST API that return this:
var time = [{"duration":"00m 25s"},{"duration":"12m 08s"},{"duration":"02m 09s"},{"duration":"01m 25s"}, {"duration":"02m 05s"}]
I want to transform this list in:
var newTime = [0.25, 12.08, 2.09, 1.25, 2.05]
Upvotes: 0
Views: 1428
Reputation: 437
You can do it as follows:
var time = [{"duration":"00m 25s"},{"duration":"12m 08s"},{"duration":"02m 09s"},{"duration":"01m 25s"}, {"duration":"02m 05s"}];
var newList = time.map((time) {
String clippedMinutes; // will get the minutes part
String clippedSeconds; //// will get the seconds part
String fullTime = time['duration']; // full time part from each Map
final splittedTimeList = fullTime.split(' '); // splits the full time
clippedMinutes = splittedTimeList[0];
clippedSeconds = splittedTimeList[1];
return double.parse('${clippedMinutes.substring(0, clippedMinutes.length - 1)}.${clippedSeconds.substring(0, clippedSeconds.length - 1)}');
}).toList();
print(newList); // output: [0.25, 12.08, 2.09, 1.25, 2.05]
If it helped you don't forget to upvote
Upvotes: 1
Reputation: 6287
My contribution:
main(List<String> args) {
final times = [{"duration":"00m 25s"},{"duration":"12m 08s"},{"duration":"02m 09s"},{"duration":"01m 25s"}, {"duration":"02m 05s"}];
var regExp = RegExp(r'(\d\d)m (\d\d)s');
var newData = times.map((e) => double.parse(e['duration'].replaceAllMapped(regExp, (m) => '${m[1]}.${m[2]}')));
print(newData);
}
Result:
(0.25, 12.08, 2.09, 1.25, 2.05)
Upvotes: 1
Reputation: 5756
You can do string manipulation using splitting string using some delimiter like space and applying transformation via map
.
void main() {
var time = [
{"duration": "00m 25s"},
{"duration": "12m 08s"},
{"duration": "02m 09s"},
{"duration": "01m 25s"},
{"duration": "02m 05s"}
];
time.map((e) {
final val = e['duration'].split(' '); // split by space
final result = val[0].substring(0, val[0].length - 1) + '.' +
val[1].substring(0, val[1].length - 1); // concat number by removing unit suffix
return double.tryParse(result); // parsing to double.
}).forEach((e) => print(e)); // 0.25, 12.08, 2.09, 1.25, 2.05
}
Upvotes: 3