Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append to a json object in angular js

I am having an object like this $scope.releases = [{name : "All Stage",active:true}];

I need to append more data to it

[
  {name : "Development",active:false},
  {name : "Production",active:false},
  {name : "Staging",active:false}
]

So the final data should be like this

[
   {name : "All Stage",active:true}
   {name : "Development",active:false},
   {name : "Production",active:false},
   {name : "Staging",active:false}
]

I tried the following code. But it is not appending.

app.controller('MainCtrl', function($scope) {
  // I am having an object like this
  $scope.releases = [{name : "All Stage",active:true}];
  // I need to appned some more data to it
  $scope.releases = [
    {name : "Development",active:false},
    {name : "Production",active:false},
    {name : "Staging",active:false}
  ]
});

Pluker Link : http://plnkr.co/edit/gist:3510140

like image 975
Sajith Avatar asked Nov 19 '13 11:11

Sajith


People also ask

How to add data to JSON object in JavaScript?

In order to add Key/value pair to a JSON object, Either we use dot notation or square bracket notation. Both methods are widely accepted. Example 1: This example adds {“prop_4” : “val_4”} to the GFG_p object by using dot notation.

How to write to a JSON file JavaScript?

If we want to write something in a JSON file using JavaScript, we will first need to convert that data into a JSON string by using the JSON. stringify method. Above, a client object with our data has been created which is then turned into a string. This is how we can write a JSON file using the fileSystem.


2 Answers

  $scope.releases = [{name : "All Stage",active:true}];
  // Concatenate the new array onto the original
  $scope.releases = $scope.releases.concat([
    {name : "Development",active:false},
    {name : "Production",active:false},
    {name : "Staging",active:false}
  ]);
like image 116
net.uk.sweet Avatar answered Sep 28 '22 01:09

net.uk.sweet


Just use the Array concat method

$scope.release = [{name : "All Stage",active:true}];
$scope.releases = [
    {name : "Development",active:false},
    {name : "Production",active:false},
    {name : "Staging",active:false}
];
$scope.releases = $scope.releases.concat($scope.release);
like image 36
Beterraba Avatar answered Sep 28 '22 00:09

Beterraba