Home > Mobile >  How to merge array into JSON array
How to merge array into JSON array

Time:10-04

I have a JSON file that I need to add Comments into and then update the file. I've created 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
    })
}

I can post the new comments into the JSON file but it overrides the past comments. I have tried to merge the older comments with the new comments with the following

$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 tried making a new function that when called combines the two and then post the 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);
    }
}

I have been going over this for the past few days now and can't seem to get it. Any help would be greatly appreciated!

EDIT

Sample Data of already existing data in JSON file

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

Want to add to this (is from html input text tag) stored as NewComment

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

Edit 2 This is how I'm getting my projects data

/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);
        }
      );
    }

I then use this to access the selected information

//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>

Then I have the following variables to post

$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");
        }
    )
};

It posts perfectly fine but it currently overrides the comments. I want to be able to add a new comment and still keep all the past comments. So I want to be able to push/add the comments into the full POST.JSON array. Hope this makes a bit more sense

CodePudding user response:

OK, updating answer after looking at provided code.

It appears you may be under the impression that $scope.projectDetails.Comments is a JSON string, when, in fact.. it's the actual Comments array.

I would try this 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 it just so happens to be a JSON string (highly unlikely), then I would update the combine function to this:

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

EDIT I'm adding another answer from my original because of the possibility things will break 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, change to:

"Comments":$scope.projectDetails.Comments

CodePudding user response:

I have figured out how to combine the two with

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

Except now it doesn't post the combined comments

$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");
        }
    )
};

It successfully posts the project except for the comments. It doesn't seem to like my combined array. When I post $scope.updatecomments it will post that but not the $scope.combinecomments.

I'll make a new question for this.

  • Related