0

How can I append to a json object.

I define the JSON as follows:

$scope.usergroupJson = {'groupId':1,'name':'CEO'}

I would like to append {'groupId':2,'name':'Director'} to the usergroup. I have tried:

$scope.usergroupJson.push({'groupId':2,'name':'Director'});

But I get an undefined error. I know this is trivial but any help would be appreciated. Thanks in advance

2 Answers 2

4

We can use like this var json = {}; json["employees"] = [];

var usergroupJson = json["employees"];
usergroupJson.push({
    'groupId': 1,
    'name': 'President'
});
usergroupJson.push({
    'groupId': 2,
    'name': 'Vice-President'
});
usergroupJson.push({
    'groupId': 3,
    'name': 'Product Manager'
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for putting it all together
4

you must usergroupJson to be array

$scope.usergroupJson = [{'groupId':1,'name':'CEO'}]

2 Comments

Thanks tried that but it is not what I am after. I would like maintain the JSON format. If I do this I end up getting something in the form of: [0], [1] I would like to get in the form: w3schools.com/json
you getting an array of objects, you cannot have on object with same key's.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.