Home > Software engineering >  Generate objects with dynamic "key" using spread operators
Generate objects with dynamic "key" using spread operators

Time:01-02

I want to generate an object where the key is the value of the index from the mapped data as shown in the code below

{data.map(({ quest, answers }, index) => {
                  <Radio.Group
                    name={index}
                    defaultValue={def}
                    onChange={(value) => {
                    setVal({...(val), index: JSON.stringify(value)}  )
                      
                    }}
                  >
                    {answers.map((ans, key) => {
                      return (
                        <Radio value={key   1}>
                          {ans}
                        </Radio>
                      );
                    })}
                  </Radio.Group>
})}

So "index" in this line

setVal({...(val), index: JSON.stringify(value)} )

should be from this line

{data.map(({ quest, answers }, index) => {

The problem is the code above returns the index value as the string "index" instead of the value of index from the mapped data i am working with

CodePudding user response:

Use it like this:-

setVal({...(val), [index]: JSON.stringify(value)} )

  • Related