TheHeroBrine
TheHeroBrine

Reputation: 17

How to select a key value for a JSON object based off a string in another JSON object

I'm setting up an API for a web app I am making to communicate with a database and need to support multiple tables.

I have a JSON object, well table of JSON objects ([{"name":"video_games", "columns":["name", "console", "wiki"]}, {"name":"game_wishlist", "columns":["name", "console", "wiki"]}]), that has the names of the tables and the columns, but I need a way to hit another JSON object to get specific data using the specifications in this object.

Example: games[i] = [table[i].name, table[i].console, table[i].wiki] is what I currently have but I need a way where I can set the name, console, and wiki to something else for other tables from the object I showed above without just setting up a ton of if statements and hard coding it.

Upvotes: 0

Views: 1354

Answers (2)

TheHeroBrine
TheHeroBrine

Reputation: 17

I think I figured it out, I can't test it here, don't have access to the db server right now but I should be able to use bracket notation (something I just learned) to do it. https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Basics#Bracket_notation

Upvotes: 0

IceMetalPunk
IceMetalPunk

Reputation: 5556

If I'm reading this right, then you should be aware that you can access object properties using similar bracket notation to arrays, letting you use a variable string for the key. So for instance, in your case you could do:

let keyName = 'wiki';
games[i][keyName] = table[i][keyName];

That would produce (assuming games[i] existed before) the same result as games[i].wiki = table[i].wiki', except now obviously you could always change the value of keyName dynamically to create and read different properties.

Upvotes: 1

Related Questions