Merging objects (associative arrays)

前端 未结 16 1257
野的像风
野的像风 2020-12-04 08:20

What’s the best/standard way of merging two associative arrays in JavaScript? Does everyone just do it by rolling their own for loop?

16条回答
  •  臣服心动
    2020-12-04 08:58

    do you want to overwrite a property if the names are the same but the values are not?

    And do you want to permanently change one of the original objects,

    or do you want a new merged object returned?

    function mergedObject(obj1, obj2, force){
        for(var p in obj1) this[p]= obj1[p];
        for(var p in obj2){
            if(obj2.hasOwnProperty(p)){
                if(force || this[p]=== undefined) this[p]= obj2[p];
                else{
                    n= 2;
                    while(this[p+n]!== undefined)++n;
                    this[p+n]= obj2[p];
                }
            }
        }
    }
    

提交回复
热议问题