Hello all I'm new to node and js - trying to make a small bot for a small discord channel , I've kinda hit a wall and can't find a solution.
I am trying to store user input data and recall it later. So far I have this to store the data as a json file.
data[user_id] = value_set
var out_data = JSON.stringify(data);
fs.writeFile('users.json', out_data);
And would look like this:
{"35978432146597841":"String.1","32146879124653147":"String.2"}
Now I want to recall the String.X value later based on the user's id. And this is where I am stuck. I figured I'd need to read the json file and transfer it to an array.
I think I successfully made it an array with the following:
var in_data = fs.readFileSync('users.json');
var data = JSON.parse(in_data);
var arr = []
for(var i in data){
arr.push([i, data [i]]);}
As... console.log(arr[1]);
shows: ['32146879124653147','String.2']
But I cannot figure out how to search that array by the user's id (user_id) to either locate the index and then split the value or even better just pull the value.
Everything I have tried to find the 'String.X' by the user_id has has failed. So what do I need to do to pull 'String.2' if I only know '32146879124653147'.
Any help will be appreciated. Thanks.
SOLUTION
var fs = require("fs");
var in_data = fs.readFileSync('users.json');
var data = JSON.parse(in_data);
var arr = [];
for(var i in data){
arr.push({
User:i,
Input:data [i]
});
}
var value = arr.find(x => x.User === id);
var f_value = value.Input;
console.log(f_value);
OR
const userfile = require("./users.json");
var f_value = userfile[userID];