[英]How can I add a object property only in case a value is not empty
I have to add new functionality to add some metadata when the referral variable is not empty.当引用变量不为空时,我必须添加新功能来添加一些元数据。 I've made this, but something in me is saying that this could be done simpler.
我已经做到了,但我内心深处的某些东西在说这可以做得更简单。
async createStripeCustomer(user, refferal) {
if (refferal) {
return stripe.customers.create({
email: user.email,
metadata: {
userId: user.id,
referral: refferal,
},
});
} else {
return stripe.customers.create({
email: user.email,
metadata: {
userId: user.id,
},
});
}
}
You can reduce the duplication like the code below您可以像下面的代码一样减少重复
async createStripeCustomer(user, refferal) { const customer = { email: user.email, metadata: { userId: user.id, }, }; if (refferal) { customer.metadata.refferal = refferal; } return stripe.customers.create(customer); }
From memory of the Stripe API, null values in metadata will not set that variable in the metadata.根据 Stripe API 的记忆,元数据中的空值不会在元数据中设置该变量。
So you can just do...所以你可以做...
async createStripeCustomer(user, refferal) {
return stripe.customers.create({
email: user.email,
metadata: {
userId: user.id,
referral: (refferal ? refferal : null)
},
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.