Tips for combining arrays into a JSON array

My task involves updating a JSON file by adding new comments to it. I have already set up an array for the new comments.

//ADDING NEW COMMENTS
//add new comment within project
$scope.updatecomments = [];
$scope.addnewcomment = function() {
    $scope.updatecomments.push({
        "Author": "test",
        "Text": $scope.NewComment
    })
}

Although I can successfully post the new comments into the JSON file, it ends up overriding the existing comments. I've attempted to merge the older comments with the new ones using the following approaches:

$scope.updatecomments = [];
$scope.addnewcomment = function() {
    $scope.updatecomments.push({"Author": "test" ,"Text": $scope.NewComment}).concat($scope.Comments, $scope.updatecomments);
}

$scope.updatecomments = [].concat($scope.updatecomments, 
    $scope.projectDetails.Comments);
$scope.addnewcomment = function() {
    $scope.updatecomments.push({
        "Author": "test",
        "Text": $scope.NewComment
    });
}

I also experimented with creating a new function that combines both sets of comments before posting them as one combined array.

$scope.combine = [];
$scope.combineComments = function (){
    var jsonStr = $scope.projectDetails.Comments;
    var obj = JSON.parse(jsonStr);
          
    obj['Comments'].push({"Author":"Test","Text":$scope.NewComment});
          jsonStr = JSON.stringify(obj);
    }
}

Despite spending several days trying different methods, I am still unable to achieve the desired outcome. Any assistance would be highly appreciated!

EDIT

Here is some sample data from the existing JSON file:

{
    "Comments":[{
        "Author": "John Doe", 
        "Text": "Work completed"
     }]
}

I need to append the following content (from an HTML input text tag) to this existing data:

{
    "Comments":[{
        "Author": "Test",
        "Text": "Project flagged"
    }]
}

Edit 2

This is how I retrieve data related to my projects:

/FIND PROJECTS - ADD TO LIST
  $scope.projectList = [];
    for (var id = 0; id < 30; id++) {
      var targetURL = 'https://happybuildings.sim.vuw.ac.nz/api/sooleandr/project.'+id+'.json';
      $http.get(targetURL).then(
        function successCall(response){
          $scope.projectList.push(response.data);
        }
      );
    }

Following this, I use the retrieved information to access specific details.

//script
$scope.showData = function(x){
 $scope.projectDetails = x;
 };
//html
<ul class = 'pList'>
   <li ng-repeat = 'x in projectList' class = 'pbList'>
     <button class = 'pbutton' ng-click = 'showData(x)'>
       <label ng-model ='pID'>Project ID: </label>{{x.ProjectID}} <br>
       <label id ='pName'>Project Name: </label> {{x.Name}} <br> 
       <label id ='bID'>Building ID: </label>{{x.BuildingID}}<br>
  <label id ='sDate'>Start Date: </label>{{x.StartDate}}
      </button>
    </li>
  </ul>

Finally, I have defined variables and functions for posting updated project details.

$scope.updateProject = function (projectDetails){
  
  var updateproject = {
    "ProjectID":$scope.projectDetails.ProjectID,
    "Name":$scope.projectDetails.Name,
    "BuildingID":$scope.projectDetails.BuildingID,
    "StartDate":$scope.projectDetails.StartDate,
    "EndDate":$scope.projectDetails.EndDate,
    "Status":$scope.projectDetails.Status,
    "ContactPerson":$scope.projectDetails.ContactPerson,
    "Contractor":$scope.projectDetails.Contractor,
    "ProjectManager":$scope.projectDetails.ProjectManager,
    "Works": $scope.projectDetails.works,
    "Comments":$scope.updatecomments,
    };
    
    $http.post("https://happybuildings.sim.vuw.ac.nz/api/sooleandr/update.project.json", updateproject).then(
      function success(){
        alert("Project Successfully Posted");
        },
        function error(){
          alert("Error: Couldn't post to server");
        }
    )
};

While the current setup allows me to post data successfully, the issue lies in the fact that it overwrites the comments section each time. My goal is to preserve all past comments and add new ones by pushing them into the full POST.JSON array. Hopefully, this clears things up a bit.

Answer №1

Alright, let's update the answer after reviewing the provided code.

It seems like there might be a misunderstanding that $scope.projectDetails.Comments is a JSON string when it's actually the Comments array itself.

Here's a suggested modification for the addnewcomment function:

//ADDING NEW COMMENTS
//add new comment within project
$scope.updatecomments = undefined;
$scope.addnewcomment = function() {
    $scope.updatecomments = $scope.updatecomments || $scope.projectDetails.Comments;
    $scope.updatecomments.push({
        "Author": "test",
        "Text": $scope.NewComment
    })
}

IF by chance it's indeed a JSON string (which is unlikely), then you can adjust the combine function as follows:

$scope.combineComments = function (){
    var jsonStr = $scope.projectDetails.Comments;
    var obj = JSON.parse(jsonStr);
          
    obj.push({"Author":"Test","Text":$scope.NewComment});
          jsonStr = JSON.stringify(obj);
    }
}

UPDATE: I'm including an additional answer based on the potential scenario of issues arising when there are no updated comments

//ADDING NEW COMMENTS
//add new comment within project
$scope.addnewcomment = function() {
  $scope.projectDetails.Comments.push({
        "Author": "test",
        "Text": $scope.NewComment
    })
}

Then in the POST request, make sure to change to:

"Comments":$scope.projectDetails.Comments

Answer №2

After experimenting, I have managed to merge the two together:

$scope.combinecomments = [];
   $scope.combine = function (){
     $scope.combinecomments.push($scope.projectDetails.Comments);
     $scope.combinecomments.push($scope.updatecomments);
   }

Unfortunately, the combined comments are not being posted as expected.

$scope.ProjectID='$scope.ProjectID';
    $scope.Name = '$scope.Name';
    $scope.BuildingID = '$scope.BuildingID';
    $scope.StartDate = '$scope.StartDate';
    $scope.EndDate = '$scope.EndDate';
    $scope.Status = '$scope.Status';
    $scope.ContactPerson = '$scope.ContactPerson';
    $scope.Contractor ='$scope.Contractor';
    $scope.ProjectManager = '$scope.ProjectManager';
    $scope.Works = '$scope.works';
    $scope.Comments ='$scope.comments';

$scope.updateProject = function (projectDetails){
  
  var updateproject = {
    "ProjectID":$scope.projectDetails.ProjectID,
    "Name":$scope.projectDetails.Name,
    "BuildingID":$scope.projectDetails.BuildingID,
    "StartDate":$scope.projectDetails.StartDate,
    "EndDate":$scope.projectDetails.EndDate,
    "Status":$scope.projectDetails.Status,
    "ContactPerson":$scope.projectDetails.ContactPerson,
    "Contractor":$scope.projectDetails.Contractor,
    "ProjectManager":$scope.projectDetails.ProjectManager,
    "Works": $scope.projectDetails.works,
    "Comments":$scope.combinecomments,
    };
    
    $http.post("https://happybuildings.sim.vuw.ac.nz/api/sooleandr/update.project.json", updateproject).then(
      function success(){
        alert("Project Successfully Posted");
        },
        function error(){
          alert("Error: Couldn't post to server");
        }
    )
};

The project posts successfully except for the comments section. It appears that there is an issue with the combined array of comments. When posting $scope.updatecomments, it works but not $scope.combinecomments.

I will create a new query regarding this matter.

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

Leveraging deep linking to launch the email application in react native

I am currently exploring the deeplink URL for the mail app on iOS. A scenario I have set up involves displaying an alert that, when the user clicks 'ok', redirects them to the default mail app. const openEmailApp = () => { if (Platform.OS ...

Tips for saving true or false values in a dynamic form?

Is there a way to store boolean values in a reactive form where a button can have the value of true or false? The goal is to be able to access the inputs of these buttons. However, I am facing an issue because there is another form on this page for text in ...

Graph not being plotted by MVC with jQPlot when utilizing the JSON dataRenderer

Currently, I am utilizing MVC4 in conjunction with jQPlot to create multiple line graphs that have DateTime values on the X-Axis. In order to fetch server data through ajax, I have implemented the following code in the controller: public ActionResult Get ...

Issue with VueJs router-link component

Whenever I click on a vuejs router-link element in my app.blade.php page navigation bar, I keep seeing an error in my console which is displayed below [Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent comp ...

Attaching a jQuery function to trigger upon an event

Can anyone help me with binding a jQuery function to a click event on an anchor link tag? I am working on ASP.net MVC with Ajax, and I want to use Ajax to display data. Any suggestions on how to bind the following function to a link click would be greatl ...

Unable to resolve eslint rule for formatting case statements within a switch statement

Looking at my sublime text window, I have a screenshot showing the eslint error that is being thrown for the switch / case statement. I'm aiming to indent 4 spaces, as shown in the code. https://i.sstatic.net/oQi63.png Here are 4 different attempts ...

Instructions for extracting the href value from an anchor tag using JavaScript within a specified string

How can I retrieve the href value of the last anchor tag in the provided content string using pure JavaScript, excluding jQuery? var contents = '<div id="content"><a href="http://www.okhype.com/wp-content/uploads/2016/12/ruffcoin-made-in-aba ...

What is the best way to integrate RequireJS into both the main and child pages?

Within my .NET Framework master page, I've integrated require.js like so: <script data-main="../../Scripts/Shared/_MaintenanceTemplateApp" src="../../Scripts/require.js"></script> Inside _MaintenanceTemplateApp.js, I have set up the conf ...

Using a loop in AngularJS to generate dynamic promises with $q.all

I'm looking to create a loop that encapsulates my second promise so that each iteration generates a new promise: var promise1 = $http({ method: 'GET', url: "https://cubber.zendesk.com/api/v2/organizations/"+id+"/users.json", d ...

Transform Python list into a JavaScript array

Seeking quick assistance from experts as I face an intriguing challenge that has me stumped. In a Python .psp file, I have a list mylist[] that is populated at runtime and a JavaScript function that requires a list to dynamically create a form object. The ...

Using Python to convert JSON to a JSON array and add the date at the start

I am working with the following JSON data: [{"UGC_TECH_PLATEFORME": "youtube", "UGC_TECH_ID": "UCu93VC-rD_TolBF4Pe5yz_Q"}] My desired result is: [{"2020-09-23":{"UGC_TECH_PLATEFORME": "youtu ...

Rearrange JavaScript Object in a Custom Sequence

Looking to filter a JSON Object (Array of Arrays) with a specific order requirement: order: ['Hors','TTC','Total général', 'verger', ' Tra'] data = [[" Tra", "100 - 149 ch", "Total"] [" Tra", "150 - 199 ...

Time Indicator (Just now or One hour earlier)

Having trouble calculating time difference using strings like "A minute ago" or "An hour ago" in Android. I've asked this question before. Is it possible to get "Time Difference" in "since/ago" format without using any library? Currently, I am extra ...

Leveraging AJAX for implementing PHP scripts

While I may not be an MVC model expert, I'm trying to keep my page design separate from my logic in order to simplify things. I have already created a basic template and now I want hyperlinks to open PHP files within the same page. For example: Next ...

Is the Selenium browser driver for node.js specifically compiled for the operating system architecture or for the processor architecture of the actual PC, or is it based on the architecture of the installed operating system?

Exploring the functionality of Node.js's os.arch(), it indicates: This function returns the CPU architecture of the operating system for which the Node.js binary was compiled. Potential values include 'arm', 'arm64', 'ia32&a ...

Delivering an XML file generated by PHP to a JavaScript parser

I'm in the process of creating a smart TV app that streams live content. The app functions properly when I provide it with a valid XML playlist. However, when I attempt to use PHP to generate the XML file (which generates without any issues), it fail ...

What steps do I need to take to modify the MUI Badge component and insert custom text inside?

Is there a way to replace the number with a label next to a new row added to my table using MUI Badge? For example, instead of displaying a number like 4, I want it to show the word "New" as shown in this image: enter image description here This is the co ...

Iterating through an array using a loop in a bash script

I am trying to create a pseudo array in bash frame1=(one two three) frame2=(one two three) frame3=(one two three) echo ${frame2[2]} This code works fine, but when I try the following: for ((fr=1; fr<=$records; fr++)) do frame$fr=(one ...

Error Encountered: Unhandled Runtime Error in Next.js with Firebase - TypeError: Unable to access the property 'initializeApp' as it is undefined

It's baffling why this error keeps appearing... my suspicion is directed towards this particular file. Specifically, firebaseAuth={getAuth(app)} might be the culprit. Preceding that, const app = initializeApp(firebaseConfig); is declared in "../f ...

Tips on setting up the table with php and javascript

My PHP and JavaScript code displays data in the wrong format. The row consists of classcode, courseNumber, courseDescription, units, time, days, room, but it's not arranged correctly. I want it to display each piece of data under its respective column ...