0

I have a payload which may or may not contain a value.

const { mainValue } = payload;

This mainValue can either only be optionaA or optionB.

I am constructing another object based on this value. How can I conditionally construct the below object. Either I need newProp1 or just newProp2. Is there an ES6 way of doing it, which will be neater.

const newObj = {
    propertyA: someValue,
    AttributeA: {
        newProp1: {
            value: optionaA
        },
        //// i need newProp1 or newProp2 in this newObj
        newProp2: {
            value: optionaB
        }
    }
}
1
  • "may or may not contain a value"... are you saying that mainValue could also be undefined? If so, what should the result look like in that case? Commented Aug 18, 2021 at 2:13

1 Answer 1

1

I believe the smallest amount of code you can have that will produce the desired output is:

const { mainValue } = payload
const newObj = {
  propertyA: someValue,
  AttributeA: {
    [`newProp${mainValue === optionaA ? 1 : 2`]: {
      value: mainValue
    }
  }
}

The ES6 feature that enables it is Computed Property Names

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

2 Comments

`${ mainValue === 'optionaA' || 'otherOption' 'email' ? '1' : '2' }`` How can I fit an OR statement?
Not sure what you are trying to achieve with the statement above. Do you mean that mainValue can be optionaA, otherOption or email and in any of this cases it should add to newProp1 and otherwise to newProp2?

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.