Implementing Node.JS ajax to update current JSON information

I am seeking assistance in updating data within a JSON file using NODE.JS. Currently, my method adds the data with the same ID as expected. However, upon receiving the data back, it eliminates the last duplicate because it encounters the old value first. I believe what I truly need to do is locate the JSON element by its ID and then replace it with the new value.

Below is the AJAX request code snippet:

putComment: function(commentJSON, success, error) {
    $.ajax({
        type: 'post',
        url: 'http://localhost:8080',
        data: JSON.stringify(commentJSON),
        success: function(comment) {
            success(comment)
        },
        error: error
    });
},

And here is my NODE code snippet:

if (req.method == 'POST') {
req.on('data', function(chunk) {
    var element = JSON.parse(chunk);
    fs.readFile("comments-data.json", 'utf8', function(err, json) {
        var array = JSON.parse(json);
        array.push(element);
        fs.writeFile("comments-data.json", JSON.stringify(array), function(err) {
            if (err) {
                console.log(err);
                return;
            }
            console.log("The file was saved!");
        });
    });
    res.end('{"msg": "success"}');
});
};

The following shows the data containing duplicate IDs:

[
  {
    "id": "c1",
    "parent": null,
    "created": "2016-08-12T19:57:21.282Z",
    "modified": "2016-08-12T19:57:21.282Z",
    "content": "test",
    "fullname": "John Clark",
    "profile_picture_url": "https://viima-app.s3.amazonaws.com/media/user_profiles/user-icon.png",
    "created_by_current_user": true,
    "upvote_count": 0,
    "user_has_upvoted": false
  },
  {
    "id": "c1",
    "parent": null,
    "created": "2016-08-12T19:57:21.282Z",
    "modified": 1471031853696,
    "content": "test 123",
    "fullname": "John Clark",
    "profile_picture_url": "https://viima-app.s3.amazonaws.com/media/user_profiles/user-icon.png",
    "created_by_current_user": true,
    "upvote_count": 0,
    "user_has_upvoted": false
  }
]

Answer №1

Need to update an item in a JSON array if it already exists? This code snippet could help:

let data = JSON.parse(json);
let isUpdated = false;

for (let i = 0; i < data.length; i++) {
   if (data[i].id === element.id) {
         data[i] = element;
         isUpdated = true;
         break;
    }
}

if (!isUpdated) {
    data.push(element);
}

fs.writeFile("comments-data.json", JSON.stringify(data), function(err) {
    if (err) {
        console.log(err);
        return;
    }
    console.log("File saved successfully!");
});

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 a script error that reads "TypeError: $ is not defined as a function

I am attempting to send an email using web services in asp.net, utilizing html and sending the information through a jquery ajax function. Below is the html form: <div class="col-md-6"> <h2>DROP ME A LINE</h2> & ...

Creating methods that are shared, privileged, and publicly accessible: A guide

Currently, some methods in one of my classes are public but can access private variables due to being privileged. This is because they are generated in the class constructor, allowing their closure to have access to the object closure. However, I am conce ...

Express app does not receive HTTP GET parameter

When making the GET request, the response received is a 404 error code. Upon sending the request to http://localhost:3000/api/watchings/?watchItemUniqueKey=5dab6083b68bd049c0b8f9ce%7C5daf5e0c8d261e5364acd8b6, the server responds with a 404 Not Found err ...

Loading STL files can sometimes lead to issues when accessing the world matrix incorrectly

While working on a three.js project, I encountered some issues with loading vertices from an STL file and converting them to world coordinates. It seems like the matrix application isn't working properly, and I suspect it could be related to the loadi ...

Expand and collapse dynamically while scrolling

// Closing Button for Main Navigation $('button#collapse-button').click(function () { $('nav#main-nav').toggleClass('closed'); }); $(window).on('scroll', function () { if ($(wind ...

What is the best way to reach a link using Selenium?

Challenge : Unable to interact with a link using JavaScript through Selenium. Attempted Solutions: element = driver.find_element_by_css_selector(a {href: "javascript:void(0)"}) resulted in a SyntaxError. element = driver.execute_script("ja ...

Retrieve the Most Recent Matching Date within an Array

In my mongoDB database, I am searching for datasets with expired date values. When I say expired, I mean that the timestamp of the last element in an array is older than a certain interval from the current timestamp (determined by a category). Each datase ...

Enabling individuals to transfer their content to Amazon S3

I have set up an S3 bucket named BUCKET in region BUCKET_REGION. I want to enable users of my web and mobile apps to upload image files to this bucket, with specific restrictions based on Content-Type and Content-Length (specifically, only allowing jpegs u ...

Using Vue.js to pass a variable from a parent component to a child component

Parent component: ShowComment Child component: EditComment I'm attempting to pass the value stored in this.CommentRecID to the child component. In the template of ShowComment, I have included: <EditComment CommentRecID="this.CommentRecID" v-if= ...

When using AutoComplete in MUI, I encountered an issue while attempting to assign a default value to the checkbox from an API. Instead of achieving the desired result, I received an error stating "(inter

Within this snippet, I am seeking to retrieve a default value from the API to populate a checkbox initially. I have employed the Material-UI Autocomplete component, which includes a defaultValue prop. Despite my efforts to utilize this prop, I am encounter ...

What steps should I take to resolve issues with my delete button using React.js, MongoDB, and Node.js?

Hello! I am facing an issue with the delete button on my website. I want users to be able to delete a promo code from the database, but for some reason, the button is not working as expected and I can't figure out what's missing. Whenever the d ...

Unable to retrieve the third attribute of a Class using Angular2's toString method

Here is the code snippet I am working with: import { Component } from '@angular/core'; @Component({ selector: 'my-app', template: ` <h1>Hello {{name}}</h1> <p><strong>Email:</strong> {{email}}< ...

Is there a way to update the button's value upon clicking it?

I've hit a roadblock in my tic tac toe game project during class, and I've been struggling for the past two days to get the X's and O's to show up. The deadline for this assignment is tomorrow! Here are the task requirements: COMPSCI20 ...

Combine arrays using underscore or lodash

Hello, I need some assistance. I have a couple of arrays containing grades with associated classes attributes like the examples below: var arr1 = [{ "id": 53, "name": "Grade 1 AppMonkeyzTest", "classes": [{ "id": 5 ...

Conceal a section of a container with the click of a button within a WordPress Plugin

I am currently utilizing a Wordpress plugin known as contact form 7 to construct an email list for an upcoming website project. The client has specifically requested that we avoid using services like mailchimp due to their preference of not sending ANY ema ...

Ways to disable the ability to close a bootstrap modal by pressing the backspace key

How can I enable the backspace button in a Bootstrap Modal form for textboxes and textareas? $('body').keydown(function (e) { if ($('#myModal').is(':visible')) { if (e.keyCode == 8) { retu ...

The issue of not displaying results in a DIV when using CakePHP 2 and jQuery

I'm having trouble creating an auto-refreshing DIV with updated data. Despite everything appearing to be correct, it's not displaying any results on the webpage. Any assistance would be greatly appreciated :) Controller: public function homeNe ...

Tips for utilizing aggregate with $near in mongoose?

I attempted to retrieve 20 random food items near a specific location. While using the find method worked, I am unsure how to utilize aggregate with $near. Data Model Schema: const foodSchema = new Schema({ foodName: { type: String, r ...

The issue arises when request-promise opens an excessive number of sockets

I'm currently working on developing a function that analyzes user input to determine the top subreddit that their comment may have belonged to based on word frequencies in training data. My database contains frequency data for words in various subredd ...

Data structures of advanced complexity within HTML data attributes

I am delighted by the existence of the html5 data attribute. It's great to be able to input a plain string into html attributes and retrieve them using jquery. However, wouldn't it be wonderful to have more than just a basic string? Is there a ...