向对象添加条目

A php script is computing me the following array:

$test = Array();
$test['a'] = Array();
$test['a']['a1'] = 'a1';
$test['a']['a2'] = 'a2';
$test['b'] = Array();
$test['b']['b1'] = 'b1';
$test['b']['b2'] = 'b2';

I'm converting this array into JSON using:

echo json_encode($test);

I'm retrieving this JSON using an Ajax call, and I'm turning this it into a JavaScript array using:

test = JSON.parse(data);

My question is: How can I add entries to this array in JavaScript? I tried:

test['c'] = [];
test['c']['c1'] = 'c1';
test['c']['c2'] = 'c2';

But then in the console test['c'] is empty (Array[0]).

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.

In javascript you can't have named indexes.

From http://www.w3schools.com/js/js_arrays.asp

Many programming languages support arrays with named indexes. Arrays with named indexes are called associative arrays (or hashes). JavaScript does not support arrays with named indexes. In JavaScript, arrays always use numbered indexes. If you use a named index, JavaScript will redefine the array to a standard object. After that, all array methods and properties will produce incorrect results.