0

I want to use the value of one object to access state variable name

for ex:

const displayName = [
    {
        name: 'name', //Actually this is the state variable name 
        displayText: 'Name: '
    },
    {
        name: 'email',
        displayText: 'E-mail ID: '
    }
]

{
displayName.map(obj =>  (
    <p>{obj.displayText}</p>
    <div>
        {this.state.data.obj.name} //Here am facing issue. The state variables are: this.state.data.name and this.state.data.email. How to replace the obj.name here
    </div>
)
} 

The state variables are: this.state.data.name and this.state.data.email. How to replace the obj.name here

If i give {this.state.data.obj.name} it's throwing an error like name not found

1 Answer 1

2

When using variables for keys, you need to use square brackets

this.state.data[obj.name]

In square brackets notation, your solution requests:

this.state['data']['obj']['name']
Sign up to request clarification or add additional context in comments.

3 Comments

ohh.. My bad.. i used this.state.data.[obj.name] After removing the dot it's working fine. Thanks man.
Are you sure that this.state['data']['obj']['name'] is equivalent to this.state.data[obj.name] in this case though?
It is not, i wrote that first one you wrote, this.state['data']['obj']['name'], is equivalent of one written in question this.state.data.obj.name,

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.