像jQuery.extend()之类的东西但是独立的? [英] Something like jQuery.extend() but standalone?

查看:92
本文介绍了像jQuery.extend()之类的东西但是独立的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法将两个配置对象合并在一起,例如:

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

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

var productionConfig = {
  url: "example.com"
};

var config = isDevelopment ? developmentConfig : jQuery.extend(developmentConfig, productionConfig);

但是,这是一个Node.js应用程序,我不想包含jQuery,我正在寻找对于类似但独立的东西。我知道我自己可以编写类似的东西,但我宁愿使用经过测试和验证的东西(有边缘情况,配置对象使用更丰富的层次结构等时会出现复杂情况。)

However, this is a Node.js app and I don't want to include jQuery and am looking for something similar but standalone. I know I could write something similar myself but I'd rather use something tested and proven (there are edge cases, complications when the config objects use richer hierarchies etc.)

编辑:简单的迭代是不够的,因为它不处理层次结构。 Underscore的也不会扩展

Edit: Simple iteration is not enough because that does not handle hierarchical structures. Neither does Underscore's extend.

推荐答案

如果您只需要扩展,然后在几行中编写它非常简单。如果你想要递归扩展,如果你想要有圆形结构,带有复杂原型链的对象等,那么完全一般地做这件事是很棘手的。如果它只是一些嵌套的普通对象,那么这应该有效:

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;
}

如果您正在寻找一个轻量级库来执行此操作(减去递归,由于上面列出的原因)以及javascript未提供的其他类似功能,请查看下划线,这也可以通过NPM获取节点。

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.

这篇关于像jQuery.extend()之类的东西但是独立的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆