Is there a method to prevent the json file from being constantly overwritten?

After running this code, I noticed that even when inputting a different userId, it still ends up overwriting the existing user instead of adding a new one as intended.

 const user = userId;
 const userObj = {[user]:valueX};
    words.users = userObj;
    fs.writeFileSync('words.json', JSON.stringify(words,null,2), finished);

The input is taken from here (readline-sync)

let userId = input.question('Enter yourUserId: ');

And of course, I am reading the file first

let words = JSON.parse(fs.readFileSync('words.json'));

Answer №1

let newUserObj = {[user]:valueX};
words.users = newUserObj;

When assigning an object to words.users, make sure it contains all existing users, not only the new one you are adding.

let updatedUserObj = {...words.users, [user]:valueX };

Answer №2

Based on the provided code snippet, it seems that words.users is being treated as an object.

if(!words.users) words.users = {};  // Ensure that words users are initialized
words.users[user] = valueY;

As a result, you will have a words.users object structured like this

{user3: valueY1, user4: valueY2}

You can then access it using

console.log(words.users[user3]); // valueY1

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I make the arrows work on a secondary slider with EasySlider1.7?

I finally managed to get 2 sliders working on my page after reading through several other tutorials. However, I am facing an issue with the Prev & Next arrows on the second slider as they don't seem to work properly. I inherited this page from someon ...

Populate object values dynamically through function invocations

Currently, I am involved in a project with a VueJS application that incorporates the following helper class and method: class BiometricMap { static get(bioType) { if (!bioType) { return BiometricMap.default(); } const bioTypes = { ...

Obtaining JSON information with Svelte

I'm currently facing a mental block. My goal is to fetch JSON data using the Youtube API. The error message I am encountering is "Cannot read property 'getJSON' of undefined". Here's the code snippet I have provided: <script> ...

What is the best way to search a map object that serves as the document ID in Firebase?

I am attempting to retrieve all fieldnames within the payload > (random doc id) objects. https://i.sstatic.net/y9703.png At this moment, my approach involves fetching other collections using the following code: async fetchPage() { const query = fir ...

Connecting Vue.JS page to my existing HTML page: A step-by-step guide

While developing my website, I faced a challenge with the structure. The home page was built using traditional HTML/CSS, while the other pages were created in Vue.js. Is there a method to connect these two different types of files? For instance, can I inc ...

Numerous sections with tabs on the webpage

I am in need of incorporating multiple tabbed sections on a single page, but unfortunately they are currently interconnected. When one tab is clicked, it impacts the others. To see this issue in action, you can visit: https://jsfiddle.net/pxpsvoc6/ This ...

Is it not possible to utilize async/await with MongoDB Model, despite it yielding a Promise?

Currently, I am facing an issue with a function in my code that is supposed to retrieve a user's inventory and then fetch the price property of each element using data from a Price Collection. Below is a snippet of the function (not the entire thing, ...

Jolt Spec - Assistance Required for Flattening an Array

Struggling with flattening the JSON data and need help to create a JOLT spec. I have tried various examples but haven't achieved the desired results. To test this, I am using the website . The sample JSON Input is as follows: { "metadata": { "t ...

Angular JS failing to display error messages

I'm experiencing difficulties displaying login validation errors with the following code. After clicking on the Login button, it redirects to the next page without showing error messages as expected. Any suggestions? index.html:- <!DOCTYPE ht ...

Is it possible to utilize JSX when developing an App using React CDN or the CRA (create-react-app) boilerplate template?

The HTML Code: <div id="app"></div> <script src="https://unpkg.com/react@latest/umd/react.development.js" crossorigin></script> <script src="https://unpkg.com/react-dom@latest/umd/react-dom.develo ...

What could be causing the response from curl_exec() in my web service?

What is causing curl_exec() to return an array in my web service? I set up a web service for sending push notifications with Firebase. Everything functions perfectly except that the server response includes the notification result, even though I did not r ...

Is there a way to prevent an iframe from being recorded in Chrome's browsing history?

I'm in the process of developing a Chrome extension that inserts an Angular application into the user's browser window to create an interactive sidebar. I've been successful in most of my goals by inserting an iframe through a content script ...

Issue with JS npm package: Unable to use import statement outside a module

I recently attempted to utilize the npm package found at https://github.com/nefe/number-precision. However, despite following the prescribed steps, I encountered some difficulties. After running npm install number-precision --save--dep, I tried impor ...

Tips for showcasing the chosen option from an autocomplete input field in a React application

Currently learning React and working on a search feature for a multi-form application. The goal is to allow users to search for a student by first name, last name, or student ID using an autocomplete text field. The options for the autocomplete text field ...

How can you make a Tempory Drawer wider in Material Components Web?

Increasing the Width of a Temporary Drawer in Material-components-web Greetings! I am currently facing an issue with Material-components-web In the provided demo here, I would like to extend the width of the Temporary drawer to accommodate additional co ...

convert an array into a JSON object using JavaScript

Is there a way to convert the following array structure arr = [{ "a":1, "b":2, "c":c }] into a JSON object format? arr = { "a":1, "b":2, "c":c } ...

Altering styles of a child component within a parent component using material-ui

I am trying to customize the appearance of a child component from within the parent component Let's take a look at the child component, MyButton.js: import ButtonComponent from '@material-ui/core/Button' const useStyles = makeStyle((theme) ...

Error loading resource: The server returned a 404 status code indicating the requested resource was not found in the Node.js socket.io

My challenge involves setting up a server with Node.js and socket.io which starts perfectly fine. However, when I attempt to access my server's site through the browser, it shows "Cannot Get /" and in the console, an error appears saying "Failed to Lo ...

Determine whether an array is void, then proceed to deactivate a button

I am attempting to prevent a button from being clickable if an array is empty, but I am encountering difficulties. <button [disabled]="(users.length ==0 )?true:false">Send mass emails</button> Within the TypeScript file: users: UsersModel[]; ...

Creating a class in JavaScript following an AJAX request

After receiving an AJAX response, the class "navtex-message" doesn't work properly when I create HTML with JavaScript. function formatNtxMessage( m ) { return '<div class="row">' + '<div class="col-lg-9">' ...