Home > Blockchain >  React render object value where key is variable
React render object value where key is variable

Time:05-13

I'm trying to render an object where each key is different. I have to display each key as a checkbox and if it is checked, I want to display the associated values if any in the values array.

My object structure is as follows:

    myObj: {
           "key1": ["val1", "val2"],
           "key2": [],
           ...
           }

I'm going through the list of keys to render the checkboxes and within, I'm using the code below for rendering the values. I have the value of the current key accessible in a property myKey.value. But if I try to use formValues.myObj.myKey.value to access the values, it complains that property myKey does not exist on type myObj.

{formValues.myObj.[`${currentKey}`].length > 0 && 
    <CustomArrayHelper
    values={formValues.myObj.currentKey}
    arrayName="test"
    onRender={(avIndex: number) => (
        <div className="my-container std-TextField">
            <FormikTextField
                name={`test.${avIndex}`}
                label={`Test`}
            />
        </div>
    )}
/>}

I need some way to dynamically specify the current key to get the values for each key. The above code returns an error.

I also have the list of possible keys available separately:

export const MyKeys = [
    {
        value: 'key1',
        label: 'key1'
    },
    ...
]

CodePudding user response:

To access values using computed property keys you need to use the bracket notation.

<CustomArrayHelper values={formValues.myObj[currentKey]} />

Also, you shouldn't put a dot when accessing properties using bracket notation, that's a syntax error. You can also remove the string template syntax, that's unnecessary.

formValues.myObj[currentKey].length
  • Related