-1

i have two lists from(list1 and list2). i processed both list as below:

list1 = jsonlist1.map((item) =>jsonDecode(item)).toList();

list2 = jsonlist2.map((item) =>jsonDecode(item)).toList();

results of my lists below:

list1 = [{woNum: 1, woDesc: installation, materials: []}, {woNum: 2, woDesc: Reinstallation, materials: []}]

list2 = [{woNum: 1, itemNum: a1, itemDesc: a1Desc}, {woNum: 1, itemNum: a2, itemDesc: a2Desc}, {woNum: 2, itemNum: a3, itemDesc: a3Desc}]

Now, i wanted to combine list1 and list2 (say FinalList), wherein the result list would like this:

FinalList = [{woNum: 1, woDesc: installation, materials: [{itemNum: a1, itemDesc: a1Desc}, {itemNum: a2, itemDesc: a2Desc}]}, {woNum: 2, woDesc: Reinstallation, materials: [{itemNum: a3, itemDesc: a3Desc}]} ]

As you can see, the FinalList merged duplicate woNum and list2 were added under 'materials' in list1 where they have equal woNum.

How can i achieve this?

Kim Lo
  • 113
  • 1
  • 9

2 Answers2

0

First merge both lists (see you already achieve it):

list1.addAll(list2);

Then select only distinct values. There are plenty of good solutions like this one.

  • hi! already tried that. but I only wanted to add list2 inside of list1 under 'materials' key. – Kim Lo Aug 08 '22 at 09:33
0

Code below is for working with List, for operators, if you want I can show with classes:

void main() {
  var list1 = [
    {
      'woNum': 1, 
      'woDesc': 'installation', 
      'materials': []
    }, {
      'woNum': 2, 
      'woDesc': 'Reinstallation', 
      'materials': [],
    }
  ];

  var list2 = [
    {
      'woNum': 1, 
      'itemNum': 'a1', 
      'itemDesc': 'a1Desc',
      }, {
      'woNum': 1, 
      'itemNum': 'a2', 
      'itemDesc': 'a2Desc',
      }, {
      'woNum': 2, 
      'itemNum': 'a3', 
      'itemDesc': 'a3Desc',
      },
  ];
  
  for (int i = 0; i < list1.length; i++) {
    for (int j = 0; j < list2.length; j++) {
      if(list1[i]['woNum'] == list2[j]['woNum']){
        (list1[i]['materials'] as List).add(list2[j]..remove('woNum'));
//         with woNum
//         (list1[i]['materials'] as List).add(list2[j]);
      }
    }
  }
  
  print('MerdanDev List with Map $list1');
// result is MerdanDev List with Map [{woNum: 1, woDesc: installation, materials: [{itemNum: a1, itemDesc: a1Desc}, {itemNum: a2, itemDesc: a2Desc}]}, {woNum: 2, woDesc: Reinstallation, materials: [{itemNum: a3, itemDesc: a3Desc}]}]
}
MerdanDev
  • 381
  • 3
  • 13
  • will try this. will give feedback thanks! – Kim Lo Aug 08 '22 at 10:31
  • hey man @MerdanDev, I tried this and it worked. thanks much! – Kim Lo Aug 09 '22 at 07:55
  • Yeah it works but I suggest to use more OOP in data strucktures and you can tell to your backend developer to learn JOIN operator if uses SQL. Such things can be managed easyly in backend and you can get only one list from your API. Thanx man for accepting – MerdanDev Aug 09 '22 at 17:34