Home > Blockchain >  how to generate a list from a maps entries with a specific key
how to generate a list from a maps entries with a specific key

Time:07-02

is it possible to extract all entries from a map, which have a specific key, to a list?

F.e. I have a map with the following form:

[
  {
    "temp": 12,
    "date": 01.07.2022,
  },
  {
    "temp": 23,
    "date": 02.07.2022,
  },
  {
    "temp": 17,
    "date": 03.07.2022,
  }
]

What I want is a list like this for the key "temp": [12, 23, 17].

CodePudding user response:

Yes, you can use the Iterator.map method on the list:

final data = <Map<String, dynamic>>[
  {
    "temp": 12,
    "date": "01.07.2022",
  },
  {
    "temp": 23,
    "date": "02.07.2022",
  },
  {
    "temp": 17,
    "date": "03.07.2022",
  }
];

final temperatures = data.map((datum) => datum["temp"]).toList();

print(temperatures); // [12, 23, 17]

CodePudding user response:

Use the map method on List which take a function taking an element of the original list (which will be a map). Extract the temp int from the map. For example:

    final result = list.map<int>((e) => e['temp'] as int).toList();
  • Related