Jan
Jan

Reputation: 357

Dart maps, how to replace specific key value in a list<map> based on its key id?

void main() {
  List<Map<String, dynamic>> products = [
    {'id': 24, 'time': '2019-11-24 00:00:00.000'},
    {'id': 36, 'time': '2019-11-23 00:00:00.000'},
    {'id': 48, 'time': '2019-11-24 00:00:00.000'},
  ];

In the code above I want to replace 'time' entry '2019-11-24 00:00:00.000' to '2019-10-26 00:00:00.000' for the 'id' 48.

Upvotes: 4

Views: 2458

Answers (2)

Akif
Akif

Reputation: 7640

You can try something like this:

   products.whereFirst((x) => x["id"] == 48)["time"] = "2019-10-26 00:00:00.000";

Upvotes: 6

Ketan Ramteke
Ketan Ramteke

Reputation: 10665

Here is another way how you can do it:

    void main() { 
      List<Map<String, dynamic>> products = [
        {'id': 24, 'time': '2019-11-24 00:00:00.000'},
        {'id': 36, 'time': '2019-11-23 00:00:00.000'},
        {'id': 48, 'time': '2019-11-24 00:00:00.000'},
      ];
      
       products = products.map((product){
        if(product["id"] == 48){
          return {...product, 'time': '2019-10-26 00:00:00.000'};
        }
         return product;
      }).toList();
      
      print(products.toString());
    }

Upvotes: 4

Related Questions