简体   繁体   中英

Dynamically adding properties to an object

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?

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

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 (eg you might not want empty strings, or number zero or anything else), though check this first:

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