0

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

1
  • 2
    Seems overkill. Just do qqParam['queryParams'].mode = 'productNumber'; Commented Mar 12, 2021 at 20:02

3 Answers 3

1

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' })

};

Sign up to request clarification or add additional context in comments.

2 Comments

Hi, Thanks for the solution but I get TS2339: Property 'queryParams' does not exist on type '{}' error if I change square brackets to qqParam.queryParams.
that's typescript trying to guess the type. If you just want to ignore that and don't have an specific type, you can do const qqParam:any = {} at the beginning
0

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

1 Comment

Hi, Thanks for the solution but I get TS2339: Property 'queryParams' does not exist on type '{}' error if I change square brackets to qqParam.queryParams.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.