我有一个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
的值,但我认为可能没有明确值的密钥会很聪明
答案 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)
答案 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);
这将从对象中过滤掉所有未定义的值(或精确的假值)。