0

Spent quite some time and googled but I can't seem to achieve this in Javascript:

PHP:

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

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

Output:

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

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

)

Well, I can, like so:

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

... but assigning values inside a look isn't possible because this:

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

... throws an error.

2
  • obj['0313A5']['price'] = "2000"; is perfectly valid... what's the error you see? Commented Jan 18, 2015 at 12:26
  • @gp. TypeError: Cannot set property 'price' of undefined Commented Jan 18, 2015 at 12:29

2 Answers 2

1

You need create empty object before assign properties to it, like this

var obj = {};

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


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

Example

Sign up to request clarification or add additional context in comments.

Comments

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']);

It is valid.

http://jsfiddle.net/9jq5esg2/

Comments

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.