1

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'
    },
    ...
]

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

3 Comments

That worked, thank you so much! The change you suggested for the name field however, gives me a cannot find name 'test' error, but keeping it the way I have it in the question works.
Great! Consider accepting & upvoting the answer if it solved your problem. You can ignore that suggestion if it doesn't work, I just made a guess there because I'm not aware of your entire code.
I've removed that part from my answer to avoid any confusion.

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.