Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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",
};
like image 554
Kay Avatar asked Feb 03 '26 01:02

Kay


2 Answers

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},
};
like image 91
Alexandre Annic Avatar answered Feb 04 '26 14:02

Alexandre Annic


Add product_id only if it is undefined

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

if(this.route.snapshot.queryParams.product_id)
   params['product_id'] = this.route.snapshot.queryParams.product_id;
like image 32
Sarthak Aggarwal Avatar answered Feb 04 '26 14:02

Sarthak Aggarwal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!