After this point:
test = JSON.parse(data);
you're not dealing with JSON anymore; test
is an object.
...and I'm turning this it into a JavaScript array using...
You're not turning it into a JavaScript array, you're turning it into a JavaScript object. JavaScript's nearest equivalent to PHP's "associative array" is an object, not an array.
To add properties to objects, you just assign to them. In your case, you're trying to create a property named c
that's an object with additional properties. Since we use objects, not arrays, for that in JavaScript, you'd create c
using {}
rather than []
. E.g.:
test['c'] = {};
test['c']['c1'] = 'c1';
test['c']['c2'] = 'c2';
or more concisely:
test.c = {};
test.c.c1 = 'c1';
test.c.c2 = 'c2';
or even more concisely:
test.c = {
c1: 'c1',
c2: 'c2'
};
What you were doing would work, because normal JavaScript arrays are really objects and so you can add arbitrary, non-element properties to them as well as using them in the more "normal" way. But in the normal case, you'd use non-array objects instead.
But then in the console test['c'] is empty (Array[0])
That's because the console is showing you the array-like aspects of the object and ignoring the non-array aspects. But test['c']
did have c1
and c2
properties, the console just didn't show them to you. Nevertheless, only use non-index property names with arrays if you have a specific reason for doing so. Otherwise, again, use non-array objects.