How to get the difference between two arrays of objects in JavaScript

前端 未结 18 1325
没有蜡笔的小新
没有蜡笔的小新 2020-11-22 04:45

I have two result sets like this:

// Result 1
[
    { value: \"0\", display: \"Jamsheer\" },
    { value: \"1\", display: \"Muhammed\" },
    { value: \"2\",         


        
18条回答
  •  自闭症患者
    2020-11-22 04:55

    I've made a generalized diff that compare 2 objects of any kind and can run a modification handler gist.github.com/bortunac "diff.js" an ex of using :

    old_obj={a:1,b:2,c:[1,2]}
    now_obj={a:2 , c:[1,3,5],d:55}
    

    so property a is modified, b is deleted, c modified, d is added

    var handler=function(type,pointer){
    console.log(type,pointer,this.old.point(pointer)," | ",this.now.point(pointer)); 
    

    }

    now use like

    df=new diff();
    df.analize(now_obj,old_obj);
    df.react(handler);
    

    the console will show

    mdf ["a"]  1 | 2 
    mdf ["c", "1"]  2 | 3 
    add ["c", "2"]  undefined | 5 
    add ["d"]  undefined | 55 
    del ["b"]  2 | undefined 
    

提交回复
热议问题