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

What is the best way to utilize an Angular service method from a controller?

As a newcomer to Angular, I have created an 'Employee Search' Service module. Let's take a look at the code: // Employee Search Service app.service('employeeSearchService', function($http, resourceServerAddress){ this.empList ...

Testing NodeJS Database Functionality using Mocha and Asserting with should.js

Currently, I am in the process of testing my NodeJS application using mocha and should. The issue I am facing is that while the first test executes smoothly, the second one fails with an error of null. Interestingly, both tests result in a valid user being ...

How to delete the last item of an array in AngularJS using scope

In my Angular controller, I have an array and a method for deleting objects. function($scope, $http){ $scope.arrayOfObjects = []; $scope.remove = function(obj){ var i = $scope.arrayOfObjects.indexOf(obj); if( i > -1 ){ ...

Error: SvelteKit server-side rendering encountered a TypeError when trying to fetch data. Unfortunately, Express is not providing a clear TypeScript stack trace

I've been monitoring the logs of the SvelteKit SSR server using adapter-node. After customizing the server.js to utilize Express instead of Polka, I noticed some errors occurring, particularly when the fetch() function attempts to retrieve data from ...

Tips for establishing control when retrieving the JSON information

I have encountered a challenge while developing a currency converter application. The issue I am facing is related to the order of data. My app fetches information from two JSON files - one containing prices and the other containing full names of currencie ...

Steps to completely eliminate all elements from an object using specific keys

I have been pondering the most efficient method to delete all elements of an object through an onClick function. The goal is for the handler to remove all elements. Despite attempts with methods like the delete keyword and filtering, clicking the clear all ...

Attempting to run driver.execute_script(gooogletag but no response was received

I have been attempting to receive responses in the console from the browser when running googletag parameters with Selenium, but unfortunately I have not been successful. Even after trying .execute_async_script('googletag.pubads()') and putting ...

Guide to successfully navigating to a webpage using page.link when the link does not have an id, but is designated by a

This is my current code snippet: async function main(){ for(int=0;int<50;int++){ const allLinks = await getLinks(); //console.log(allLinks); const browser = await puppeteer.launch({ headless: true }); const page = await browser.newPa ...

Simulate a keyboard key being pressed and held for 5 seconds upon loading the page

Is it possible to create a script that automatically triggers an event to press and hold down the Space key for 5 seconds upon page load, without any user interaction? After the 5 seconds, the key should be released. It is important to emphasize that abso ...

Is it possible to modify the CSS of a single class when hovering over a child class of a different and unrelated class?

I am struggling with CSS combinators, especially when dealing with nested div, ul, and li elements. My issue involves changing the CSS of a div with the class "H" when hovering over li elements with the class "G". Since all of this is contained within a s ...

Guidelines on fetching API data in React JS

When attempting to retrieve data from the OpenWeather API, I encountered an issue. The API's response is expected to be in JSON format, but instead, I received an error message: SyntaxError: Unexpected token < in JSON at position 0 useEffect(() =& ...

Unraveling a dynamic field with Jackson's deserialization functionality

Consider the Json representations below: { "id": "id1", "version": "id1", "license": { "type": "MIT" } } { "id": "id1", "version": "id1", "license": "MIT" } { "id": "id1", "version": "id1", "licenses": [ { "type ...

Crashes within an HTML5 Canvas

Having recently started to explore Javascript and working with canvas elements, I've encountered a roadblock when trying to implement collision detection for the canvas walls. Typically, I have a small square drawn on the canvas that I can move aroun ...

Utilizing JsonQuery to retrieve organized JSON data within filter.js

I recently discovered the amazing filter.js script, which can be found at https://github.com/jiren/filter.js. It has been incredibly helpful in my projects. var FJS = FilterJS(products, '#products', { template: '#productfinder-template& ...

What is the best way to achieve a full width table in an HTML format on a smartphone browser?

Apologies for my limited English proficiency. I am currently working on creating a horizontal scrollable table in HTML. My goal is to make the width of the table span beyond the browser's viewing area, so that sticky cell functionality can be implem ...

Can jQuery be used to change the functionality of a submit button, such as toggling between show, hide, and submit options?

I am having trouble toggling a button to either submit a form on click or reveal an input field, depending on whether the user clicks outside the input field to hide/collapse it. The issue arises when the user dismisses the input field and the submit butto ...

The process of updating UseContext global state in React Native and ensuring that the change is reflected across all screens

Struggling with updating global state values using React useContext on different screens? Attempting to change theme color in the App, but changes only appear on the current screen and not carried over to others? Looking for assistance in resolving this ...

Building interactive web forms with real-time validation using CodeIgniter

I'm looking for a way to use ajax (jquery library) to validate my forms. Specifically, I have a form that requires a minimum password length of 6 characters. Currently, I have implemented the validation rule as follows, $this->form_validation-> ...

Attempting to comprehend the error message "TypeError: list indices must be integers or slices, not str"

### The following line executes without errors health_data_json = resp.json()["data"]["metrics"] ### However, this line results in a "TypeError: list indices must be integers or slices, not str" message energy_data_json = resp.json()[ ...

Is it impossible to modify an enumerable attribute within a JSON.stringify replacer function?

I'm having some trouble trying to serialize non-enumerable properties within the replacer function. Can someone point out what might be going wrong in this code snippet? Any help would be greatly appreciated. var obj = {x:1,y:2}; Object.definePrope ...