Home > Software design >  combine/merge two lists json and remove duplicates
combine/merge two lists json and remove duplicates

Time:08-08

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?

CodePudding user response:

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.

CodePudding user response:

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}]}]
}
  • Related