Karim Ali
Karim Ali

Reputation: 2453

how to add a new key value to the same key in an object in JavaScript based on a condition?

I have done it using ...qqParam['queryParams'] but is this the right approach?

const qqParam = {};
if (view) {
  qqParam['queryParams'] = { view: view };
}
if (productNumber) {
  qqParam['queryParams'] = { ...qqParam['queryParams'], mode: 'productNumber' }; 
}

Upvotes: 0

Views: 74

Answers (3)

Fabio Lopez
Fabio Lopez

Reputation: 527

I think your approach is correct, just a couple things that can simplify your code while keeping it readable:

  1. if you know you'll always need queryParam attribute, you can call it like this: qqParam.queryParam without the [], if the key of the attribute is dynamic then you're doing it ok by passing it as a variable qqParam[variable].
  2. you're in both ifs modifying the same value so you might consider doing that on one statement:

qqParam.queryParams = {

...(view && {view}),

...(productNumber && {mode:'productMode' })

};

Upvotes: 1

Ran Turner
Ran Turner

Reputation: 18036

Your approach is fine. one improve that you can do is not to use : {'view' : view}. you can just use {view} as the default key will be the value name when you not specifing one.

Also, i guess that 'productNumber' should be the variable productNumber and not the string 'productNumber'.

const qqParam = {};
if (view) {
   qqParam['queryParams'] = { view };
}
if (productNumber) {
   qqParam['queryParams'] = { ...qqParam['queryParams'], mode: productNumber }; 
}

Upvotes: 0

Karl Lopez
Karl Lopez

Reputation: 1099

Your sample code works but you can simplify it.

You don't need to use the square brackets when assigning a property to the object unless it contains a symbol, a special character or a computed property name.


const qqParam = {};

if(view) {
    qqParam.queryParams = { view };
}

if(productNumber) {
    qqParam.queryParams = { ...qqParam.queryParams, mode: 'productNumber' }; 
}

Upvotes: 0

Related Questions