我有以下对象:
let params = {
limit: limit,
offset: 15,
status: "completed",
product_id: this.route.snapshot.queryParams.product_id,
};
上述对象包含过滤我的数据源的参数。
this.route.snapshot.queryParams.product_id
是查询/获取参数
?product_id=123
但是,如果该值不存在,则它是未定义的。因此,如果此值未定义,我不想将 product_id
成员添加到参数对象。
如果未定义,对象应该如下所示:
let params = {
limit: limit,
offset: 15,
status: "completed",
};
最佳答案
内联解决方案:
let params = {
limit: limit,
offset: 15,
status: "completed",
...this.route.snapshot.queryParams.product_id && {product_id: this.route.snapshot.queryParams.product_id},
};
或更短:
const product_id = this.route.snapshot.queryParams.product_id
let params = {
limit: limit,
offset: 15,
status: "completed",
...product_id && {product_id},
};
关于javascript - 仅当对象不是 undefined 时才向对象添加属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52852567/