Enhance JSON by updating and appending data

I am currently working with a JSON file stored separately. Here is the code snippet I am using:

[{"username":"John","id":"1","points":[{"type":"gold","amount":1}]},
{"username":"Mark","id":"2","points":[{"type":"bronze","amount":13}]},
{"username":"Mayou","id":"3","points":[{"type":"silver","amount":10}]}]
let username = "John";
let id = 1;
let amount = 1;
let type = silver;

const configDirectory = path.resolve(process.cwd(), "essentials");

let tableSend = JSON.parse(readFileSync(path.join(configDirectory, '../essentials/tableSend.json')));
const exist = tableSend.filter(item => item.id == id).length > 0;
if (exist == true) {

} else {
  const values = {
    username: username,
    id: id,
    points: [{
      type: type,
      amount: amount
    }]
  }
  tableSend.push(values);
  let newData = JSON.stringify(tableSend);
  writeFileSync(path.join(configDirectory, '../essentials/tableSend.json'), newData);
}

How can I update existing data or add new data to the JSON? The desired result should look like this:

[{"username":"John","id":"1","points":[{"type":"gold","amount":1},{"type":"silver", "amount":1}]},
{"username":"Mark","id":"2","points":[{"type":"bronze","amount":13}]},
{"username":"Mayou","id":"3","points":[{"type":"silver","amount":10}]}]

Or how do I adjust the counts accordingly?

[{"username":"John","id":"1","points":[{"type":"gold","amount":50}]},
{"username":"Mark","id":"2","points":[{"type":"bronze","amount":13}]},
{"username":"Mayou","id":"3","points":[{"type":"silver","amount":10}]}]

Answer №1

Make sure to use the tableSend.find() method in order to locate the specific object with an id:1, and then proceed to append data into its points array. In cases where the object is not found, simply include the new user along with their details within the array.

const existingUser = tableSend.find(item => item.id == id);
if (existingUser) {
  existingUser.points.push({
    type: type,
    amount: amount
  });
} else {
  const newUserValues = {
    username: username,
    id: id,
    points: [{
      type: type,
      amount: amount
    }]
  }
  tableSend.push(newUserValues);
}
let updatedData = JSON.stringify(tableSend);
writeFileSync(path.join(configDirectory, '../essentials/tableSend.json'), updatedData);

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

Utilizing promise values within asynchronous functions

I know this question has been asked multiple times, but I'm facing a situation where I need to retrieve a variable created within a promise. The examples I've come across involve using .then to access the data, but in my case, I need to work with ...

Issue encountered while serializing data in next.js when utilizing getServerSideProps function

Encountering An Error Error: The error message "Error serializing .myBlogs returned from getServerSideProps in "/blog"" keeps popping up. I'm facing a problem while attempting to log the data! Initially, when I was fetching data using use ...

I am looking to send the JSON data to the backend in Grails by utilizing square brackets instead of curly brackets

this is the back-end section in Grails used to fetch data def addMessageA() { JSONObject requestJson= request.JSON; Message message = new Message(); message.message = requestJson.message; message.category = Category.get(requestJson.cId); ...

Ways to determine changes made to a table in MSSQL

What is the most efficient method to determine if a table or row in MSSQL (using Node.js) has been modified? I am looking to verify whether my database has been updated within the past 30 minutes. If no updates have been made in the last half hour, I pla ...

Encapsulation of JSON data with variable declaration

After generating a json data using the PHP code below: $index = array(); foreach($rows as $row) { $row['data'] []= (object) []; $index[$row['cat_id']] = $row; } // build the tree foreach($index as $id => &$row) ...

Error message 'Access is Denied' occurs when using Angular.js xhr.open()

Currently, I am developing an angular web application that needs to be compatible with IE10. One of the requirements is to make a cross-domain call to our enterprise salesforce server. When using Chrome (not officially supported but commonly used for devel ...

Display the complete image once the loading process is finished on Angular 12

When retrieving image src via API from the server, I aim for the image to only be displayed once completely loaded. In the meantime, I would like a skeleton outline to be shown during the loading process (images are segmented into sections and the skeleton ...

Adjusting Media Queries according to the browser window's zoom level

Is there a way to detect the browser width dynamically? For instance, can I adjust the CSS styling based on zoom adjustments like ctrl + or ctrl -? By "box," I am referring to a perfectly square shape. So, when the browser width is 100%, I want a layout wi ...

Unable to abort AWS Amplify's REST (POST) request in a React application

Here is a code snippet that creates a POST request using the aws amplify api. I've stored the API.post promise in a variable called promiseToCancel, and when the cancel button is clicked, the cancelRequest() function is called. The promiseToCancel va ...

Can node.js be run on a server alongside another JavaScript file?

I have developed a small web application on my personal server. It consists of a few HTML, CSS, and JavaScript files. I am looking to incorporate Node.js with the following simple code: var mysql = require('mysql'); var fs = require('fs&apos ...

Interactive canvas artwork featuring particles

Just came across this interesting demo at . Any ideas on how to draw PNG images on a canvas along with other objects? I know it's not a pressing issue, but I'm curious to learn more. ...

Is there a way to automatically update a webpage?

When two computers, pc1 and pc2, are on the same page and pc1 changes the status of a field, is there a way to update pc2's aspx page without needing to refresh it? ...

What is the method for determining if parsing is necessary or unnecessary?

Let's talk JSON: var datat= {"Model": "Model A", "Datase": [ { "Id": "DatchikSveta11", "Group": 2, "State": "on", "Dat ...

The command "npm run build" is failing and encountering errors within the webpack project

Today, when I ran npm run build in the terminal, my project stopped running and displayed 90 errors and 13 warnings. It was working fine yesterday, so I'm not sure what the issue could be. The only change I made was to a line of JavaScript code that i ...

Retrieve an image URL from the content field in a JSON file and display it as an image in an Android app

I've successfully managed to parse JSON data, extracting and displaying all the necessary information. One particular string within my JSON is labeled as Content. This particular string is quite extensive, containing a large amount of text. Hidden som ...

Discovering terms in JavaScript

Looking at a sorted array like this: var arr = [ "aasd","march","mazz" ,"xav" ]; If I'm searching for the first occurrence of a letter that starts with "m", how can I achieve it without iterating through the entire array? ...

Discovering the precise location of the required() file

When using the require function in the `node` console with commands such as require('path') or require('assert'), how can I determine the absolute path of the file that was loaded? I have searched everywhere for a clear answer without ...

Creating functionality in Ionic to allow for the dynamic addition of buttons to the navigation bar

I have a navigation bar and I would like to include a save button on it for just one screen. After going through various blogs, I found that the general advice is to declare buttons in the view rather than accessing them in a controller. But still, isn&apo ...

The start "NaN" is not valid for the timeline in vis.js

Whenever I attempt to make a call, an error message pops up saying Error: Invalid start "NaN". I've looked everywhere online for a solution with no success. Below are the timeline options: timeline: { stack: true, start: new Date(), end: ...

ReactJS Error: Cannot find reference to 'require'

I'm currently implementing the DRY concept in React JS by attempting to reuse the same HTML partial across different files. Here is the partial: var AdminMenu = React.createClass({ getInitialState: function() { return {}; }, render: function() ...