简体   繁体   中英

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.

您应该解析文件内容,以便将原始数据转换为JavaScript对象。

myarray[001] = JSON.parse(fs.readFileSync("data/001"));

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM