javascriptangular

Add property to object only if it is not undefined


I have the following object:

let params = {
  limit: limit,
  offset: 15,
  status: "completed",
  product_id: this.route.snapshot.queryParams.product_id,
};

The above object contain parameters that filter my data source.

this.route.snapshot.queryParams.product_id is a query/get parameter

?product_id=123

However if this value is not present it's undefined. So I do not want to add product_id member to the parameters object if this value is undefined.

If it is undefined the object should look like:

let params = {
  limit: limit,
  offset: 15,
  status: "completed",
};

Solution

  • Inline solution:

    let params = {
      limit: limit,
      offset: 15,
      status: "completed",
      ...this.route.snapshot.queryParams.product_id && {product_id: this.route.snapshot.queryParams.product_id},
    };
    

    Or shorter:

    const product_id = this.route.snapshot.queryParams.product_id
    let params = {
      limit: limit,
      offset: 15,
      status: "completed",
      ...product_id && {product_id},
    };