1

I want to access json with a value in input.

My function and json

 import pet3 from '../../utils/pet3' //my json file
 const getValueFromJson = (value) => {

 const data = pet3
 console.log(data.components) //it works fine
 console.log(data.value) // it is undefined              
 }
 getValueFromJson("components")
Oğulcan Karayel
  • 395
  • 1
  • 7
  • 19
  • 1
    Duplicate of https://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable – limido May 21 '20 at 13:21

1 Answers1

2

You can access the object keys dynamically by using the square brackets:

import pet3 from "../../utils/pet3"; //my json file
const getValueFromJson = (value) => {
  const data = pet3;
  console.log(data[value]);
};
getValueFromJson("components");

Edit:

Alternately, you can install and use a 3rd party library like lodash which provides the _.get() method that can be used like this:

import get from "lodash/get"; // if not installed, run `npm install lodash --save-dev`

const getValueFromJson = (value) => {
  const data = pet3;
  console.log(get(data, value, "default value")); /* returns "default value" if key is undefined. */
};
getValueFromJson("components.filename");
Bassem
  • 3,582
  • 2
  • 24
  • 47