有没有办法简化有条件地使用node.js向对象添加值?

时间:2015-09-06 09:35:30

标签: javascript node.js dry

我有一个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的值,但我认为可能没有明确值的密钥会很聪明

4 个答案:

答案 0 :(得分:3)

此处有共享功能,可以重构为函数。

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

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

答案 1 :(得分:0)

Jaromanda X's anwer的修改:

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;

答案 2 :(得分:0)

您可以使用xtend等模块。

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

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

答案 3 :(得分:0)

我现在正在做的是:

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

这将从对象中过滤掉所有未定义的值(或精确的假值)。