0

I have these values stored in a .json as a very basic xp system (im aware of corruption issues, like to learn json before moving to db)

"267752827723492576":{"xp":308,"level":1}, "267752827723492576":{"xp":308,"level":1}

i want to import userid, xp, and level into a variable so i can make a leaderboard command, i already have working code for doing the comparison and sorting (below) . "user" being the variable containing my data from the json file

var users = {
    "":{"xp":0,"level":0},
    "":{"xp":0,"level":0},
    "":{"xp":0,"level":0},
    "":{"xp":0,"level":0},
    "":{"xp":0,"level":0},
      };

          let board = Object.entries(users)
                        .map(([key, val]) => ({id: key, ...val}))
                        .sort((a, b) => b.xp- a.xp);

          console.log(board);

1 Answer 1

1

Post is not clear, but you just wan't to import json?

const users = require("path_to.json")

You can also use fs.readFile alongside JSON.parse

Also instead of using an object to store the data you can use an array

with this format: (same format after you used your map method)

[{ id: "", xp: 200, level: 2}]

For preformance both have ups and downs, for actually getting a user by id an object is probably faster, but since you have to use Object.entries and map it probably evens out

Incase you do switch to array, here's how you would fetch a user

// ... just stands for data here, not the deconstructing or rest syntax
const json = [{...}, {...}];
const user = json.find(f => f.id === "the-id-here");
Sign up to request clarification or add additional context in comments.

Comments

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.