0

I have a json array object like below

$scope.Json = [{ Id:"5464", Class:"9", Rank:"4" }]

I want to add a item "Name":"Vicky" to the Json. So that my result should be as below.

$scope.Json = [{ Id:"5464", Class:"9", Rank:"4", Name:"Vicky" }]

I am new to angular, can anyone help on this?

user1733952
  • 49
  • 2
  • 6
  • Publicate of http://stackoverflow.com/questions/736590/add-new-attribute-element-to-json-object-using-javascript - please search before asking a new question. – lin Mar 28 '17 at 15:47

2 Answers2

2

Use Array map() method.

DEMO

var json = [{ Id:"5464", Class:"9", Rank:"4" }];

json.map(function(item) {
  item.Name = 'Vicky'; 
});

console.log(json);
Debug Diva
  • 26,058
  • 13
  • 70
  • 123
0

First of all, the object $scope.Json is not a JSON but a string. To get a JSON, you need to parse the string like the following:

$scope.Json = JSON.parse(<string>) ;

Second, your input is a peculiar JSON as it is an array with one element (in its turn having 3 elements. I guess you wanted this:

$scope.Json = JSON.parse({ Id:"5464", Class:"9", Rank:"4" }) ;

Once you have this, you can add the element you want as:

$scope.Json.Name = "Vicky" ;
FDavidov
  • 3,505
  • 6
  • 23
  • 59