How to append to a json object in angular js

痴心易碎 提交于 2019-12-18 14:55:54

问题


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


回答1:


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



回答2:


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



回答3:


user angular.extend() to extend the object angular extend

you can also use angular.merge() angular merge



来源:https://stackoverflow.com/questions/20070790/how-to-append-to-a-json-object-in-angular-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!