Something like jQuery.extend() but standalone?

前端 未结 3 646
不思量自难忘°
不思量自难忘° 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:19

    If all you need is extend, then it's pretty simple to write that in a couple of lines. If you want recursive extension, it's tricky to do that completely generically if you want have circular structures, objects with complex prototype chains, etc. If it's just some nested plain objects, then this should work:

    function extend (target, source) {
      target = target || {};
      for (var prop in source) {
        if (typeof source[prop] === 'object') {
          target[prop] = extend(target[prop], source[prop]);
        } else {
          target[prop] = source[prop];
        }
      }
      return target;
    }
    

    If you're looking for a lightweight library that does this (minus the recursion, for the reasons listed above) and other similar functions not provided by javascript, look at Underscore which is available via NPM for node too.

提交回复
热议问题