deep extend (like jQuery's) for nodeJS

后端 未结 11 856
情歌与酒
情歌与酒 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);
            }
        });
    }
    
    0 讨论(0)
  • 2020-12-13 18:03

    I know this is an old question, but I'd just like to throw lodash's merge into the mix as a good solution. I'd recommend lodash for utility functions in general :)

    0 讨论(0)
  • 2020-12-13 18:03

    Sharped version called whet.extend.

    I re-write node-extend with CoffeeScript and add travis-ci test suite, because I need deep coping in Node for myself, so now it is here.

    And yes, I think in some case its absolutely correctly to use deep merge, for example I use it at config works, when we are need to merge default and user branches together.

    0 讨论(0)
  • 2020-12-13 18:10

    Please use the built-in util module:

    var extend = require('util')._extend;
    
    var merged = extend(obj1, obj2);
    
    0 讨论(0)
  • 2020-12-13 18:10

    You also can use my version of extend plugin https://github.com/maxmara/dextend

    0 讨论(0)
  • 2020-12-13 18:14

    node.extend does it deep and has familiar jQuery syntax

    0 讨论(0)
提交回复
热议问题