Reputation: 8379
I am new to JSON and Here is my First JSON Object
var First = {
"a" : [{}]
};
I want to add the below object to "a" in "First"
var a = {"1":"One","2":"Two"};
I have tried below code
First.a[First.a.length-1] = a;
It is not working.I assume that there are some syntax mistakes in this. Please help me on this.
Upvotes: 1
Views: 186
Reputation: 700192
That's not a "JSON object". There isn't even any such thing. It's a Javascript object.
It's not working as you expect as you are not adding an item to the array, you are replacing the last item.
Just use the push
method to add an item at the end of the array:
First.a.push(a);
Upvotes: 1
Reputation: 46647
You should use Array.push().
var myObject = {
myArrayOfObjects: []
};
var newObject = {
1: '1',
2: '2'
};
myObject.myArrayOfObjects.push(newObject);
Upvotes: 1
Reputation: 14400
it you want to add it, you're looking for First.a.push(a)
if you want to replace the last element:
First.a[First.a.length-1] = a;
if you want to append a to the last element:
First.a[First.a.length-1]['a'] = a;
or
First.a[First.a.length-1].a = a;
if it's none of these, please add the expected json in your question.
Upvotes: 1