List Add Map Object

Viewed 72

I have two lists as below. How can I combine the elements in the list within themselves?

var cars = [
    {"id" : 1, "title" : "BMW"},
    {"id" : 2, "title" : "Toyota"}
  ];
  var attr = [{"hp" : 250}, {"hp" : 130}];

How can I get it to print out this way?

[{"id": 1, "title": BMW", "hp": 250}, {"id": 2, "title": "Toyota", "hp": 130}]
3 Answers

I assume both list have same number of items and each item needs to be merged to the item at the same index on the other list.

In that case, you can either use a for loop to iterate through those lists and merge or you can just use forEach method.

cars.asMap().forEach((index, value) => () {
    return value.addAll(attr[index]);
}());
  
print(cars);

Output:

[{id: 1, title: BMW, hp: 250}, {id: 2, title: Toyota, hp: 130}]
var cars = [
{"id" : 1, "title" : "BMW"},
{"id" : 2, "title" : "Toyota"}
];
var attr = [{"hp" : 250}, {"hp" : 130}];
var newList = [];
for (int i=0;i<cars.length;i++){
Map newCar = {
  "id":cars[i]["id"],
  "title":cars[i]["title"],
  "hp":attr[i]["hp"],
};
newList.add(newCar);
}
print(newList);

For me, that's the simplest solution that comes to my mind

If you want to do it without using a third list then you must follow this. This is simple logic and can be used for larger lists as well.

  List<Map> cars = [
    {"id" : 1, "title" : "BMW"},
    {"id" : 2, "title" : "Toyota"}
  ];
  List<Map> attr = [{"hp" : 250}, {"hp" : 130}];
  
  
  for(int i = 0; i<cars.length;i++){
    for(int j = 0; j<attr.length;j++){
      if(i==j){
        cars[i].addAll(attr[j]);
      }
      
    }
    
  }
 print(cars);
  

DartPad for this

Related