简体   繁体   中英

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

I have a node.js script where I'm adding keys to an object if either a local or global value exists. I feel as though there should be a good way to simplify this, but I'm not seeing it. Is there a way to make this code less verbose:

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

I've thought about adding all the keys to the object and just assigning them a value of local.thirdSetting || thirdSetting local.thirdSetting || thirdSetting , but I don't think it would be smart to potentially have keys with an undefined value.

There is shared functionality here which can be refactored into a function.

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

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

Modification of 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;

You could use a module like xtend .

It allows you to use an arbitrary number of objects that will be merged into one object. Consider that the right-most object takes precedence over all the others.

This requires your global variables to be grouped into a single object, which is probably a good idea anyway.

What I'm doing now is this:

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

This will filter all undefined values (or falsy values to be precise) from the object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM