有没有一种方法可以简化使用 node.js 有条件地向对象添加值?

Is there a way to simplify conditionally adding values to an object with node.js?

我有一个 node.js 脚本,如果存在局部值或全局值,我会在其中向对象添加键。我觉得好像应该有一个很好的方法来简化这个,但我没有看到它。有没有办法让这段代码不那么冗长:

  var object = {
    defaultKey: defaultValue
  };

  // Add some conditional keys based on local and global settings
  // With local settings taking precedence
  if (local.firstSetting || firstSetting) {
    entry.firstSetting = local.firstSetting || firstSetting;
  }
  if (local.secondSetting || secondSetting) {
    entry.secondSetting = local.secondSetting || secondSetting;
  }
  if (local.thirdSetting || thirdSetting) {
    entry.thirdSetting = local.thirdSetting || thirdSetting;
  }

我考虑过将所有键添加到对象并为它们分配一个值 local.thirdSetting || thirdSetting,但我认为可能具有未定义值的键是不明智的。

修改Jaromanda X的答案:

var t;
if( t = local.firstSetting  || firstSetting  )  entry.firstSetting  = t;
if( t = local.secondSetting || secondSetting )  entry.secondSetting = t;
if( t = local.thirdSetting  || thirdSetting  )  entry.thirdSetting  = t;

这里有共享功能,可以重构为函数。

function getSetting(name) {
    var setting = local[name] || globals[name] || entry[name];
    if(setting) {
        entry[name] = setting;
    }
}

getSetting('firstSetting');
getSetting('secondSetting');
getSetting('thirdSetting');

您可以使用像 xtend 这样的模块。

它允许您使用任意数量的对象,这些对象将合并为一个对象。考虑最右边的对象优先于所有其他对象。

这需要将您的全局变量分组到一个对象中,无论如何这可能是个好主意。

我现在做的是:

  var pick = require('lodash.pick');
  var identity = require('lodash.identity');

  var object = pick({
    defaultKey: defaultValue
    firstSetting: local.firstSetting || firstSetting,
    secondSetting: local.secondSetting || secondSetting,
    thirdSetting: local.thirdSetting || thirdSetting
  }, identity);

这将从对象中过滤掉所有未定义的值(或准确地说是虚假值)。