Accessing JSON values using variables

JW
1 min readFeb 25, 2021

--

Some simple options for accessing JSON values with dynamic keys.

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:

  1. 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.

--

--

JW
JW

Written by JW

Front-End Software Engineer, and avid learner of history.

No responses yet