具有命名索引的多维关联数组

时间:2015-01-18 12:22:08

标签: javascript

花了很长时间并用Google搜索,但我似乎无法在Javascript中实现这一目标:

PHP:

$items['01A']['price'] = "$30";
$items['01A']['description'] = "Description1";

$items['02B']['price'] = "$60";
$items['02B']['description'] = "Description2";

输出:

Array
(
    [01A] => Array
        (
            [price] => $30
            [description] => Description1
        )

    [02B] => Array
        (
            [price] => $60
            [description] => Description2
        )

)

嗯,我可以这样:

var obj = {
    '0113A5' : {
        'price' : '1200',
        'discount' : '5'
    },
    '0213A5' : {
        'price' : '1800',
        'discount' : '0'
    }
};

...但是在一个外观中分配值是不可能的,因为:

obj['0313A5']['price'] = "2000";
//or
obj.0313A5.price = "2000";

...抛出错误。

2 个答案:

答案 0 :(得分:1)

您需要在为其指定属性之前创建空对象,例如

var obj = {};

obj['0113A5'] = {};
obj['0113A5'].price = '1200';
obj['0113A5'].discount = '5';


obj['0213A5'] = {};
obj['0213A5'].price = '1800';
obj['0213A5'].discount = '0';

Example

答案 1 :(得分:0)

var obj = {
            '0113A5' : {
                'price' : '1200',
                'discount' : '5'
            },
            '0213A5' : {
                'price' : '1800',
                'discount' : '0'
            }
        };

obj['0113A5']['discount'] = '222';
alert(obj['0113A5']['discount']);

obj['0113A5'].discount = '333';
alert(obj['0113A5']['discount']);

这是有效的。

http://jsfiddle.net/9jq5esg2/