DiscordJS: updating specific segment of JSON object

I am currently working on a Discord bot using discord.JS that involves creating a JSON database with specific values. I'm wondering how I can modify the code to edit a particular object within the JSON instead of completely replacing it.

if (message.content.startsWith("/requestdeposit")){
             
             let moneyrequest = message.content.split(" ");
                 
             moneyrequest.shift();
     
             moneyrequest = moneyrequest.join(" ");
     var num69 = moneyrequest;
             if(isNaN(num69)){
             
                 message.channel.send("You did not enter a valid number.")
                  }
                  else
                  {
                     
                     

                      requester = message.author.id;
                      
                      let link = require('./money.json')
                     var userid1 = "";
                     userid1 = message.author.id;
                     
                   link = {[userid1]: {
                          name: `${message.author.username}`,
                          balance: `${moneyrequest}`
                        }
                     }
                       
                      
                     const stringifiedrequest = JSON.stringify(link, null, 4,'\t');
                     
                     
                       

                     fs.writeFile('money.json', stringifiedrequest, (err) => {
                         if (err) {
                             throw err;
                         }
                         console.log("JSON data is saved.");
                     });
                 }
                  }

An example JSON structure:

{
"427861168284106762": {
    "name": "woodendoors7",
    "balance": "1"
}}

Is there a way I can update only the object related to the user running the command, replacing their "name" and "balance", while preserving the rest of the JSON data?

Answer №1

Instead of replacing the JSON Object with

link = {[userid1]: {
                      name: `${message.author.username}`,
                      balance: `${moneyrequest}`
                    }
                 }

you can simply update it by assigning

link[userid]: {...}

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

Encountering an error while including ngmin in the r.js build file

Currently, I am attempting to utilize ngmin with requirejs's r.js as outlined in a guide found here. Unfortunately, I have encountered issues and cannot seem to make it work. Despite installing both ngmin and requirejs globally and locally using npm, ...

Ways to constrain checkbox choices to only one within an HTML file as the checklist with the checkboxes is being created by JavaScript

I am working on developing an HTML dialogue box to serve as a settings page for my program. Within this settings page, users can create a list of salespeople that can be later selected from a drop-down menu. My current objective is to incorporate a checkbo ...

Unable to render page with scrapy and javascript using splash

I am currently trying to crawl this specific page. Following a guide on Stack Overflow to complete this task, I attempted to render the webpage but faced issues. How can I resolve this problem? This is the command I used: scrapy shell 'http://local ...

Detecting the Escape key when the browser's search bar is open - a step-by-step guide

One feature on my website is an editor window that can be closed using the Escape key. The functionality is implemented in JavaScript: $(document).keyup( function(e) { // Closing editor window with ESCAPE KEY if(e.which == 27) { // Clic ...

Error: Unable to authenticate due to timeout on outgoing request to Azure AD after 3500ms

Identifying the Problem I have implemented SSO Azure AD authentication in my application. It functions correctly when running locally at localhost:3000. However, upon deployment to a K8s cluster within the internal network of a private company, I encounte ...

Using Mysql to insert data depending on the condition determined by a select query

I have a challenging task ahead - executing a complex query that involves inserting data based on a comparison of the number of rows and the values within those rows. Here's what I aim to accomplish: - Retrieve all media records with a specific "post_ ...

Showing post response (XMLHttpRequest) on Chrome extension interface instead of Python console

I am currently developing a Chrome extension that sends a post request with information about the specific URL being browsed by the user to Flask (local host). A web scraping process is then carried out on this URL to determine a category based on the obta ...

Activate the jQuery click event by specifying the URL

On my webpage, I have a jQuery click function that loads multiple HTML pages into a specified div. I am looking to set specific URLs that will trigger this event, like test.com#about <script type="text/javascript"> $(document). ...

In the present technological landscape, is it still considered beneficial to place Javascript at the bottom of web pages?

As a beginner in web programming, I've recently delved into Javascript. A hot debate caught my attention - where should javascript be placed, at the top or at the bottom of a webpage? Supporters of placing it at the top argue that a slow loading time ...

What is the optimal method for saving and organizing data in SQL?

I currently have a MySQL table containing data that is displayed in an HTML table. Using JavaScript and drag & drop functionality, I am able to locally sort this table. My question is, what is the most effective method for saving these sorting changes? W ...

Encountering an error while attempting to publish content on a different domain

Currently, I am attempting to send data in form-urlencoded format using Axios. Below is the code snippet: const qs = require("qs"); const axios = require("axios"); const tmp = { id: "96e8ef9f-7f87-4fb5-a1ab-fcc247647cce", filter_type: "2" }; axios .po ...

The Like and increment buttons seem to be unresponsive when placed within a FlatList component

Issues with the like and increment button functionality within the FlatList Here are my constructor, increment, and like functions: constructor(props){ super(props); this.state = { count: true, count1: 0, }; } onlike = () => ...

When using a Webhook on Parse.com's after_save function, the resulting JSON data

Upon reviewing my Parse.com Error logs, I came across the following error: [E2015-09-28T12:40:37.531Z]vWEB after_save triggered for MPPChatRoom for user gI8UxW2JNa: The input causing the issue is as follows: {"object":{"counter":0,"createdAt":"2015-09-18 ...

Is there a way to extract the query string from a file in order to query the database using ExpressJS?

I am having trouble with this code snippet as it doesn't seem to be working properly. var content = fs.readFileSync('/home/diegonode/Desktop/ExpressCart-master/views/partials2/menu8xz.hbs', 'utf8' ); req.db.products.find( co ...

Tips on appending a parameter to an image URL using JavaScript

On my website, I am able to insert images with specified width and height using this code: <img src="image.php?w=100&h=100"> I would like the image size to change based on the device screen width. For screens smaller than 600px, I want to displa ...

What is causing the UI to change every time I add a tag to refresh the web view?

Recently, I added a pull-to-refresh feature to my React Native webview app using the react-native-pull-to-refresh library. After implementing the tag, I noticed that the UI got rearranged with the webview shifted down and the top half occupied by the pull- ...

What is the best way to create a custom query in node.js for retrieving data from mongodb?

Currently, I am utilizing MongooseJS and have a data model set up like this: var UserSchema = new Schema({ username: {type: String, required: true}, location: {type: [Number], required: true}, // [Long, Lat] created_at: {type: Date, default: D ...

Developing a transparent "cutout" within a colored container using CSS in React Native (Layout design for a QR code scanner)

I'm currently utilizing react-native-camera for QR scanning, which is functioning properly. However, I want to implement a white screen with opacity above the camera, with a blank square in the middle to indicate where the user should scan the QR code ...

Learn how to create a registration form using Ajax, PHP, and MySQL

So far I've been working with HTML <form id="account_reg" action="reg.php" method="post"> <div id="response"></div> <div class="input"> <label>Login</> <input name="login" type="text" class=" ...

How can you eliminate a specific element from an HTML document?

Utilizing localStorage can be tricky when it comes to keeping the JSON file hidden from being displayed on the HTML page. One approach I used involves sending the JSON file to the client once and then performing all logic using that file. To prevent the JS ...