1

I have an object named Object1 which is third party object & I'm putting in properties inside it.

Object1.shoot({
'prop1':prop_1,
'prop2':prop_2,
'prop3':prop_3
});

Now I want the key 'prop1' to be added as property to Object1 only when prop_1 has some value. Otherwise I do not want to add it,

Whats the best way to do it?

stry
  • 11
  • 4

2 Answers2

2

You can check each property in for loop first.

var params = {
    'prop1':prop_1,
    'prop2':prop_2,
    'prop3':prop_3
};

for (var param in params) {
    if (typeof params[param] === 'undefined') {
        delete params[param];
    }
}

Object1.shoot(params);
Boris Zagoruiko
  • 12,705
  • 15
  • 47
  • 79
1

You can make a helper function to add the property if defined:

function addProp(target, name, value) {
  if(value != null) {
    target[name] = value
  }
}

var props = {}
addProp(props, 'prop1', prop_1)
addProp(props, 'prop2', prop_2)
addProp(props, 'prop3', prop_3)

The above does a null check instead of an undefined check. You can change as appropriate (e.g. you might not want empty strings, or number zero or anything else), though check this first:

Community
  • 1
  • 1
steady rain
  • 2,246
  • 3
  • 14
  • 18