Usually when accessing JSON you would access the value as follows.
object.keyName
But you can also access JSON as follows:
object[keyName] // or object["KeyName"]
This can be useful for two reasons:
- It allows accessing values of keys that are multiple words
const object = {
"This is the key name" : "value"
}object["This is the key name] // "value"
2. To dynamically input the key being searched ie. to use variables.
const randomFunctionToAccessValueOfKey= (keyName) => {
return object[keyName];
}
This can be really handy, for example where you want to keep repetitive functionality limited to one function.
handleChange = event => {
const { value, name } = event.target;
this.setState({ [name]: value });
};
The above example demonstrates a commonly used handleChange
functionality used in a typical React form. Instead of repeating the handleChange
logic for each type of input this allows an easy and DRY (Don’t-Repeat-Yourself) way of handling form state changes.