deep extend (like jQuery's) for nodeJS

后端 未结 11 858
情歌与酒
情歌与酒 2020-12-13 17:27

I am struggling with deep copies of objects in nodeJS. my own extend is crap. underscore\'s extend is flat. there are rather simple extend variants here on stackexchange, bu

11条回答
  •  無奈伤痛
    2020-12-13 18:00

    This works for deep object extension... be warned that it replaces arrays rather than their values but that can obviously be updated how you like. It should maintain enumeration capabilities and all the other stuff you probably want it to do

    function extend(dest, from) {
        var props = Object.getOwnPropertyNames(from), destination;
    
        props.forEach(function (name) {
            if (typeof from[name] === 'object') {
                if (typeof dest[name] !== 'object') {
                    dest[name] = {}
                }
                extend(dest[name],from[name]);
            } else {
                destination = Object.getOwnPropertyDescriptor(from, name);
                Object.defineProperty(dest, name, destination);
            }
        });
    }
    

提交回复
热议问题