Home > Enterprise >  use nodejs var as json object statement?
use nodejs var as json object statement?

Time:02-08

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

CodePudding user response:

Brackets to access the variable key should work

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

CodePudding user response:

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

  •  Tags:  
  • Related