0

how do I use a nodejs var inside a json statement, I dont realy have the required vocabulary to explain but here is my simplifyed code:

test.json:

{
"test1":["test1.1", "test1.2"],
"test2":["test2.1", "test2.2"]
}

test.js:

const json = require("./test.json")
function myFunction(TYPE){
return(json.TYPE[0])
}
console.log(myFunction("test1"))

as I use the "type" var it tries to uses it as an json statement or object but obviously there is no "type" there only is "test1" and "test2" but it interprets as "type" instead

2

2 Answers 2

0

Brackets to access the variable key should work

function myFunction(TYPE){
return(json[TYPE][0])
}
0
0

In JavaScript, json objects are pretty much same as plain JS objects. You need to use string as an index to access properties:

// This could be your json file, its almost the same
// Just require it like you did instead of using const JSON like i am
const json = {
"test1":["test1.1", "test1.2"],
"test2":["test2.1", "test2.2"]
}

function myFunction(TYPE){
// Access the json by using keyword directly as index string
  return(json[TYPE])
  // because TYPE is a string, TYPE[0] would mean first letter of TYPE string
}

function myFunctionDeeper(TYPE){
  // To access a field and array in that field
  return(json[TYPE][0])
}

console.log(myFunction("test1"))
console.log(myFunctionDeeper("test1"))

// example for what happens when accessing string by index
console.log("test1"[0])

Read more about objects here

8
  • thank u very much, I never thought about using 2 vars, I allways tried like json[type][0] or json[type[0]] but simply writing 2 vars like type = json[type] and type[0] works This took me so long
    – phi zim
    Feb 7, 2022 at 14:31
  • There is no such thing as a "json object". Require on a JSON file parses the JSON to a JavaScript object. Using the correct terminology helps. Feb 7, 2022 at 14:37
  • @HereticMonkey I used json object to refer to the origin of the object, which is json file. Sorry if this is too confusing.
    – user3133
    Feb 7, 2022 at 14:40
  • @HereticMonkey did you just change the correct answer due to terminology you do not understand?
    – user3133
    Feb 7, 2022 at 14:42
  • @user3133 Please refrain from accusing people when you don't understand how the site works. I (as a user just like you) can not change the accepted answer. Only the OP (asker) can do that. Also, I understand the terminology, and my comment was correcting your incorrect use of the terminology. Feb 7, 2022 at 14:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.