FatalKeystroke FatalKeystroke - 4 months ago 12
Node.js Question

Populate Javascript Array with JSON Data

I am attempting to load a large set of JSON files into an array to be referenced later but Node keeps stating they're undefined. I have code along the lines of:

var myarray = [];

(...)

var loading_num = 001; // will be incremented in a loop to load data
myarray[loading_num] = fs.readFileSync("data/" + loading_num);

(...)

var reference_num = "001"; // the number being used to pull the appropriate record

(...)

console.log(myarray[reference_num].name); // just testing to attempt to decipher why it doesn't work, I'll actually be using the data obviously


Each JSON file does have a value named
name
and I have not implemented logic to load all of them yet as I am still just trying to get one to work.

Am I misunderstading something about Javascript arrays or objects? What am I doing wrong? There's a lot of files and they can vary in number so I have to load them in some similar fashion.

Answer

First of all. fs.readFileSync reads arbitrary files. If you know your file is JSON and you want to convert it to js you need to parse it using JSON.parse.

Then 001 is 1 if you want it to be a string wrap it with quotes '001'

Array indices starts from 0.

var myarray = [];
myarray.push(JSON.parse(fs.readFileSync("data/001")));
console.log(myarray[0].name);

Or

var myarray = {}; // use object
myarray['001'] = JSON.parse(fs.readFileSync("data/001"));
var reference_num = "001";
console.log(myarray[reference_num].name);