ppshein ppshein - 5 months ago 8
AngularJS Question

How to add new json node in javascript

Here is my current json response.

[{"id":1,"name":"Yangon","$$hashKey":"object:170"}]


But I want to add new node to above json as follow,

[{"id":1,"name":"Yangon","$$hashKey":"object:170", "township_id": 1, "township_name": "Ahlone"}]


Please help me how to do it. Thanks in advance.

Answer

You need to store your response into a variable (it probably already is) and just add whatever key/values you want:

Example

var arr = [{ "id": 1, "name": "Yangon", "$$hashKey": "object:170" }];

arr[0]['township_id'] = 1;
arr[0]['township_name'] = 'Ahlone';

Result

[{"id":1,"name":"Yangon","$$hashKey":"object:170","township_id":1,"township_name":"Ahlone"}]