Something like jQuery.extend() but standalone?

前端 未结 3 643
不思量自难忘°
不思量自难忘° 2020-12-07 00:48

I\'m looking for a way to merge two configuration objects together, something like:

var developmentConfig = {
  url: \"localhost\",
  port: 80
};

var produc         


        
3条回答
  •  离开以前
    2020-12-07 01:22

    One more example of simple standalone function for future pilgrims across this question with protection from merge of the properties of different types:

    function extend(obj) {
        Array.prototype.slice.call(arguments, 1).forEach(function(source) {
            if (source) {
                for (var prop in source) {
                    if (source[prop].constructor === Object) {
                        if (!obj[prop] || obj[prop].constructor === Object) {
                            obj[prop] = obj[prop] || {};
                            extend(obj[prop], source[prop]);
                        } else {
                            obj[prop] = source[prop];
                        }
                    } else {
                        obj[prop] = source[prop];
                    }
                }
            }
        });
        return obj;
    }
    

    Usage:

    extend({ name:'Maria', address:{ city:'Moscow', street:'Lenina str, 52' } }, { name:'Marianna', address:{ zip:1200003 }})
    => { name:'Marianna', address:{ city:'Moscow', street:'Lenina str, 52', zip:1200003 } }
    

提交回复
热议问题