use nodejs var as json object statement?

98
July 26, 2022, at 09:00 AM

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

Answer 1

Brackets to access the variable key should work

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

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

Rent Charter Buses Company
READ ALSO
Store files on mongodb database or server

Store files on mongodb database or server

I have a website built on MongoDB which has files to be downloaded by users other than images ( it can be a software installer orexe file

72
Best practices to handle Cart

Best practices to handle Cart

I am trying to create a E-commerce project using MERN stack and was wonderingHow to go about creating a cart for a user

103
Js Node Selenium Try-Catch Js Error not working

Js Node Selenium Try-Catch Js Error not working

I'm trying to simulate clicking on an element that is rendered after a certain iteration of documentreadyState='complete'

63