0

Is there a way to pass a parameter into a function and use it to dynamically access json data? (Assume all my syntax is correct. I'm just wondering if this is possible)

I'm using React to try and pass a parameter into a functional component and get data from the json file to type out {Component(thing1)} instead of {Component({jsondata.thing1.greeting}, {jsondata.thing1.closing})} for each key pair I need to use. I can already access all the data, I would just rather have all the data calls in the component file and pass in a single parameter that corresponds to the object I need, rather than have to pass in each key as a separate parameter.

This is kind of what I'm thinking:

//json data
{
    jsondata: {
        thing1: {
            greeting: "Hey"
            closing: "Bye"
        }
        thing2: {
            greeting: "Sup"
            closing: "See ya"
        }
        thing3: {
            greeting: "Yo"
            closing: "Farewell"
        }
    }
}

// js file
function = (INSERT) => {
    console.log ({data.INSERT.greeting}, {data.INSERT.greeting})
}

function(thing1) //should return "Hey, Bye"
function(thing2) //should return "Sup, See ya"

2 Answers2

0

If you want to specify dynamic key use could use square brackets syntax. for example: json_data[dynamic_key]

function = (INSERT) => {
    console.log ({data[INSERT].greeting}, {data[INSERT]greeting})
}
Dinesh undefined
  • 5,490
  • 2
  • 19
  • 40
0

What you're looking for is Bracket Notation [] Property Accessors

These allow you to dynamically get data from Objects like so:

key = 'a string'
object = {
  'a string': 412123,
  'another one': 440
}

console.log(object[key])
console.log(object['another one'])

What you're using is the Dot Notation . property accessor. Try this one instead.

const yourFunction = (INSERT) => console.log({data[INSERT].greeting}, {data[INSERT].greeting})
Andria
  • 4,712
  • 2
  • 22
  • 38