How to merge two arrays of JSON objects - removing duplicates and preserving order in Javascript/jQuery?

后端 未结 4 679
自闭症患者
自闭症患者 2020-12-29 12:38

jsfiddle link: http://jsfiddle.net/vN6fn/1/

Assume I have these 2 objects:

var obj1 = { data: [ 
                      {id:1, commen         


        
4条回答
  •  执笔经年
    2020-12-29 13:25

    Here is a straight jQuery solution:

    function mergeDeep(o1, o2) {
        var tempNewObj = o1;
    
        //if o1 is an object - {}
        if (o1.length === undefined && typeof o1 !== "number") {
            $.each(o2, function(key, value) {
                if (o1[key] === undefined) {
                    tempNewObj[key] = value;
                } else {
                    tempNewObj[key] = mergeDeep(o1[key], o2[key]);
                }
            });
        }
    
        //else if o1 is an array - []
        else if (o1.length > 0 && typeof o1 !== "string") {
            $.each(o2, function(index) {
                if (JSON.stringify(o1).indexOf(JSON.stringify(o2[index])) === -1) {
                    tempNewObj.push(o2[index]);
                }
            });
        }
    
        //handling other types like string or number
        else {
            //taking value from the second object o2
            //could be modified to keep o1 value with tempNewObj = o1;
            tempNewObj = o2;
        }
        return tempNewObj;
    };
    

    Demo with complex objects. I have turned this into a blog-post showing the difference between jQuery's .extend() and my script here.

提交回复
热议问题