Home > Software engineering >  How can i make this condition dynamic?
How can i make this condition dynamic?

Time:09-28

fieldName is a variable and is dynamic and the value can be either media, media2 or media3.

How can i make "media" be either media, media1 or media3.

instead of doing this...

if(fieldName === 'media') {
const newObj = { ...objComponent, media: json.media };
} if(fieldName === 'media2') {
const newObj = { ...objComponent, media2: json.media };
} else {
const newObj = { ...objComponent, media3: json.media };
}

CodePudding user response:

You can pass key with brackets [] like below

const newObj = { ...objComponent, [fieldName]: json.media };

That would help you pass dynamic string keys to your object.

CodePudding user response:

You can use object's dynamic keys, where variable name can be used as key inside the object. The syntax is surrounding the key with [] and the variable as the key.

// fieldName = media or media2 or media3
const newObj = { ...objComponent, [fieldName]: json.media};
  • Related