javascript - 仅当对象不是 undefined 时才向对象添加属性

标签 javascript angular

我有以下对象:

   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/

相关文章:

javascript - 没有文件阅读器的 Angularjs 图像预览

javascript - Angular2 Material ViewportRuler 单元测试错误

javascript - 当定义的任何变量在内存中具有 0 或 1 个转储值时,null 如何表示 "no value"?

JavaScript 方法中 "splice(a,b,...)"的 Java 等效方法

Angular 2 : No provider for (injected) service

javascript - Angular 8 : formControlName inside component multiple nested levels below

javascript - Angular:显示两个类组件之间的差异

javascript - 当用户在 Javascript 中使用鼠标滚轮开始滚动时,如何确定用户将滚动多少像素

javascript - AmCharts ChartCursor 在图例上隐藏值

javascript - jquery 不返回带有类名的元素