Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get array of particular key from List<Map<String,dynamic>> in DART

Tags:

flutter

dart

I have a list with the below values:

List<Map<String, dynamic>> arrayTest = [{'id':'1','name':'test1'},{'id':'2','name':'test2'},{'id':'3','name':'test3'},{'id':'4','name':'test5'}];

I want to get all id values from the arrayTest variable into another List<dynamic> type list.

I'm new to flutter, I've tried the .map() function but not getting any idea how to do this.

like image 958
Dharini Avatar asked Jan 26 '23 07:01

Dharini


2 Answers

This will help you !

List<dynamic> newList= arrayTest.map((m)=>m['id']).toList();
//replace m['id'] with your field !
like image 126
Naveen Avidi Avatar answered Feb 02 '23 20:02

Naveen Avidi


I am not sure what you wanted, also please add expected output in your asked question.

Is that what you wanted:

void main() {
List<Map<String,dynamic>> arrayTest = [{'id':'1','name':'test1'},{'id':'2','name':'test2'},{'id':'3','name':'test3'},{'id':'4','name':'test5'}];

  List list=[];
  for(var array in arrayTest){
    list.add(array['name']);

  }
  print(list);
}

OR
without for loop

void main() {
List<Map<String,dynamic>> arrayTest = [{'id':'1','name':'test1'},{'id':'2','name':'test2'},{'id':'3','name':'test3'},{'id':'4','name':'test5'}];


  List list= arrayTest.map((array)=>array['name']).toList();
  print(list);
}



output:

[test1, test2, test3, test5]
like image 28
Anirudh Sharma Avatar answered Feb 02 '23 20:02

Anirudh Sharma