Kay
Kay

Reputation: 19680

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",
};

Upvotes: 13

Views: 12280

Answers (14)

mrienstra
mrienstra

Reputation: 622

Quite a few of the answers here fail to store falsy* values (null, false, 0, '', etc.). If you wish to ignore only undefined values:

let b = null, o;
o = { a: 1, ...(b !== undefined && { b }) };
// {a: 1, b: null}

The parenthesis (above) are optional, but your linter may prefer them. Without:

let b = undefined, o;
o = { a: 1, ...b !== undefined && { b } };
// {a: 1}

*: https://developer.mozilla.org/en-US/docs/Glossary/Falsy

Upvotes: 0

Dmitri Algazin
Dmitri Algazin

Reputation: 3456

Came across same issue, created a function for that, easy to reuse:

const isEmpty = (value) => (value === undefined || value === null || value === '');
const isNotEmpty = (value) => !isEmpty(value);

const newEntry = (key, value) => {
  const newObj = {};
  if (isNotEmpty(value)) {
    newObj[key] = value;
  }
  return { ...newObj };
};

Code would look like this now:

const params = {
  limit,
  offset: 15,
  status: 'completed',
  ...newEntry(product_id, this.route.snapshot.queryParams.product_id),
};

Upvotes: 0

Nitish Narang
Nitish Narang

Reputation: 4184

You can do this with object destructuring as below

var param = {
            limit: 5,
            offset: 15,
            status: "completed",
            product_id: undefined,
        };
var { product_id, ...rest } = param

param = { ...(product_id && { product_id }), ...rest }

Upvotes: 0

Alexandre Annic
Alexandre Annic

Reputation: 10768

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},
};

Upvotes: 27

Nagaraja R
Nagaraja R

Reputation: 39

How about constructing params object with 3 members and later append based on condition.

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

Upvotes: -1

Lia
Lia

Reputation: 11982

you can also try:

let param = { product_id:this.route.snapshot.queryParams.product_id }
params = this.route.snapshot.queryParams.product_id ? {...params, ...param} : params ;

Upvotes: 1

Torsten Weggen
Torsten Weggen

Reputation: 151

This should do the work:

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

if (this.route.snapshot.queryParams.product_id) {
   params["product_id"] = this.route.snapshot.queryParams.product_id
}

Upvotes: 0

Sajal Preet Singh
Sajal Preet Singh

Reputation: 379

There are a number of ways to achieve this. I'll point out two of them. you can simply use an if statement for adding product_id field

let product_id = this.route.snapshot.queryParams.product_id;
if(product_id) {
    params.product_id = product_id;
}

or

you could use split operator

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

Upvotes: 0

Jonathan Stellwag
Jonathan Stellwag

Reputation: 4267

What do you think about the following

const constantParams= {
   limit: limit,
   offset: 15,
   status: "completed",
}
let yourDynamicObject = this.route.snapshot.queryParams.product_id 
? {...constantParams, product_id: this.route.snapshot.queryParams.product_id}
: this.paramsWichAreAlwaysThere

Upvotes: 0

Nurbol Alpysbayev
Nurbol Alpysbayev

Reputation: 21901

Try this

  const product_id = this.route.snapshot.queryParams.product_id;

  let params = Object.assign({
            limit: limit,
            offset: 15,
            status: "completed"
        }, product_id ? {product_id} : {});

Upvotes: -1

Sarthak Aggarwal
Sarthak Aggarwal

Reputation: 2312

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;

Upvotes: 5

Jonathan Goodman
Jonathan Goodman

Reputation: 371

Personally I think you should let product_id be undefined and do a check if its there later down the line but you could do the following:

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

if(this.route.snapshot.queryParams.product_id) {
  params['product_id'] = this.route.snapshot.queryParams.product_id;
}

Upvotes: 0

OliverRadini
OliverRadini

Reputation: 6466

When I've done this in the past, I've gone with something similar to the example below. I feel like there's probably a better way of doing this, but I've yet to find one.

const removeUndefinedValues = objectIn => Object.keys(objectIn)
  .reduce((prev, curr) => {
    return objectIn[curr] !== undefined ?
      {
        ...prev,
        [curr]: objectIn[curr]
      } : prev
  }, {})

let paramsOne = {
    limit: 0,
    offset: 15,
    status: "completed",
    product_id: undefined,
}

let paramsTwo = {
    limit: 0,
    offset: 15,
    status: "completed",
    product_id: "A value",
}

console.dir(removeUndefinedValues(paramsOne))
console.dir(removeUndefinedValues(paramsTwo))

Upvotes: 0

Learning is a mess
Learning is a mess

Reputation: 8277

I don't think you can do this inline, but

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

will get the job done.

Upvotes: 0

Related Questions