actually this code works as expected but, if I do input a different userId, it still do overwrite the existing user (not the file) and the ideia was to add another one
const user = userId;
const userObj = {[user]:valueX};
words.users = userObj;
fs.writeFileSync('words.json', JSON.stringify(words,null,2), finished);
input comes from here (readline-sync)
let userId = input.question('Enter yourUserId: ');
and yes i'm reading the file first
let words = JSON.parse(fs.readFileSync('words.json'));
CodePudding user response:
const userObj = {[user]:valueX}; words.users = userObj;
The object you assign to words.users
needs to include all the existing users and not just your new one.
const userObj = {...words.users, [user]:valueX };
CodePudding user response:
From your code it looks like words.users is an object and in that case
if(!words.users) words.users = {}; // Make sure the words users are created
words.users[user] = valueX;
This would give you an words.users object that look like this
{user1: valueX1, user2: valueX2}
And you could access like this
console.log(words.users[user1]); // valueX1