Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
736 views
in Technique[技术] by (71.8m points)

flutter - compare two json object list and delete the common object from first json object list in dart

I am trying to achieve the below result in dart but not able to find any solution

Example

List<Model> a=[{'a': 'Ram1', 'b': 'a+'},{'a': 'Ram2', 'b': 'a-'},{'a': 'Ram3', 'b': 'b-'},{'a': 'Ram4', 'b': 'ab+'},{'a': 'Ram5', 'b': 'ab-'}]
List<Model> b=[{'a': 'Ram1', 'b': 'a+'},{'a': 'Ram2', 'b': 'a-'}]
# I want the result to be like
List<Model> a=[{'a': 'Ram3', 'b': 'b-'}, {'a': 'Ram4', 'b': 'ab+'},{'a': 'Ram5', 'b': 'ab-'}]
question from:https://stackoverflow.com/questions/65602217/compare-two-json-object-list-and-delete-the-common-object-from-first-json-object

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
    List<Map<String, dynamic>> a=[{'a': 'Ram1', 'b': 'a+'},{'a': 'Ram2', 'b': 'a-'},{'a': 'Ram3', 'b': 'b-'},{'a': 'Ram4', 'b': 'ab+'},{'a': 'Ram5', 'b': 'ab-'}];
    List<Map<String, dynamic>> b=[{'a': 'Ram1', 'b': 'a+'},{'a': 'Ram2', 'b': 'a-'}];
    List<Map<String, dynamic>> c=List.from(a);

    a.forEach((elementA) {
      b.forEach((elementB) {
        int keysMatched = 0;
        elementB.keys.forEach((key) {
          if(elementA.containsKey(key) && elementA[key] == elementB[key]){
            keysMatched++;
          }
        });
        if(keysMatched == elementB.keys.length){
          c.remove(elementA);
        }
      });
    });

    print(c); // [{a: Ram3, b: b-}, {a: Ram4, b: ab+}, {a: Ram5, b: ab-}]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...