1

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

3 Answers 3

1

After much help from Jay this is the answer I came up with.

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 === userID);
var f_value = value.Input;
console.log(f_value);

OTHER

I have since found an easier way to accomplish the above, without fs, or creating an array.

const userfile = require("./users.json");
var f_value = userfile[userID];
Sign up to request clarification or add additional context in comments.

Comments

0

You need to push the items separately and then loop over it skipping by 2 elements in the array.

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(i);
  arr.push(data[i]);
}

console.log("Printing arr...");
  for(var i=0; i<arr.length; i++) {
    console.log("arr[" + i + "]= " + arr[i]);
  }

  // Check if 32146879124653147 is found

  console.log("Checking 32146879124653147...");
  for (var i=0; i<arr.length; i+=2) {

    if (arr[i] === "32146879124653147") {
      console.log("Found " + arr[i+1]);
    }
  }

3 Comments

Thanks for the answer, I am probably reading it wrong but the above looks like you need to know the string value. But that will be unknown and is what the user is storing. I will only know the users ID and will be using that to find the data they stored.
Changed it based on user ID value.
The first for loop works and prints out each array. Printing arr... arr[0]= 35978432146597841,String.1 arr[1]= 32146879124653147,String.2 and continues to Checking 32146879124653147... but then it stops nothing is printed after. If instead of console.log("Found " + arr[i+1]); I do var value = arr[i+1] console.log(value); it prints undefined.
0

You can use find(). In your example, it will return the first key/value that matches, or undefined if there is no match.

var in_data = fs.readFileSync('users.json');
var data = JSON.parse(in_data);

let obj = {}
for(var i in data){

obj[i]:data [i];

let value = obj.find(value => id)
//if id = '32146879124653147' 
// then the 32146879124653147: 'String.2' key/value would be returned

5 Comments

Maybe I'm doing something wrong, but let value = arr.find(value => id) is only returning the first part of the array. So arr[0]. Even for troubleshooting purpose I manually type in value = arr.find(value => '32146879124653147'), it is not returning ['32146879124653147','String.2'] it is returning ['35978432146597841',"String.1']
I am not sure, I thought that would return the array. Could you store it in a key value pair instead of the array when you build it? arr.push({[i]: data[i]}). then use the find().
I can try, and thought doing so, but couldn't figure out how. And how would that alter the find().
Just changing "arr.push([i, data [i]])" to "arr.push({[i]: data[i]})" didn't change the return. With obj[i]:data [i]; I get an error "Unexpected token :" I added a brace "}" at the end thinking that might be the issue but no change.
I finally got it thanks for all the help - it led me to figuring it out. I don't know if its the most elegant but it works. I'll post the solution under my question and answer it as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.