简体   繁体   English

如何仅在值不为空的情况下添加对象属性

[英]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.

相关问题 如果仅知道其他属性,如何在数组中搜索对象属性值? - How can I search for an object property value in an array if I only know a different property? 如何在对象数组中运行forEach并为具有空字符串的object属性设置值? - How can I run a forEach through my array of objects and set a value for the object property that has an empty string? 我可以向当前的“ this”对象添加属性吗? 怎么样? - Can I add a property to the current “this” object? How? 如何有条件地向对象添加属性 - How can I add a property to an object conditionally 如何在Javascript中向“此”对象添加属性 - how can i add a property to 'this' object in Javascript 当值为空时如何将键/值对添加到Javascript对象? - How can I add a key/value pair to a Javascript object when the value is empty? 只有在 typescript 中为真时,我才能向 object 添加属性吗? - Can I add property to object only if true in typescript? 如何使用for循环在空对象中设置属性? - how can i set the property in empty object using for loop? 仅在定义值时将属性添加到 object - Add property to object only if value is defined 如何在两个对象数组中搜索匹配的属性,然后在值为true时添加属性 - How can I search two object arrays for matching properties and then add a property if a value is true
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM