fanbondi
fanbondi

Reputation: 1047

Initialize Nested Associative array in Javascript

I have an associative array with the following structure

[location][product] and then [count] and [date] leaf entries

I am trying to initialize it using the code below

summary = {};
if(location in summary == false && product in summary == false){
        summary[location][product] = {};
}

then then iterating over an object of sales and assigning values using

summary[location][product]["count"] = count;
summary[location][product]["date"] = countDate;

but I am getting the error below, what am I missing

Type Error: summary[location] is undefined 

Upvotes: 0

Views: 972

Answers (3)

Archenoth
Archenoth

Reputation: 354

The problem with your code is you cannot assign multiple levels of undefined or null object members by name simultaneously, so something like this will fail:

var obj = {};
obj.member.member = someValue; // Will fail

To solve this, you could always initialize a "skeleton" of the object using an object literal before using it. That way you can avoid having to initialize the object level by level.

summary = {"location": {"product": {}}};

Upvotes: 1

jonasnas
jonasnas

Reputation: 3580

The problem is that your code:

summary = {};
if(location in summary == false && product in summary == false) {
    summary[location][product] = {};
}

will never set product because if location is not in summary then you wont be able to set product with:

summary[location][product]

since you can't set a product property of null (location)

And later when you try to access location property with:

summary[location][product]

the same issue happens. Location is null and you can't access its property 'product'.

P.S. if location and property is not a variable they must be in quotes like 'location' or 'product'

Upvotes: 1

ryguy21
ryguy21

Reputation: 46

You need to define each nested object as you go. So instead of

summary = {};
if(location in summary == false && product in summary == false) {
    summary[location][product] = {};
}

you need to type

summary = {}

if (!(location in summary)
    summary[location] = {}

if (!(product in summary[location]))
    summary[location][product] = {}

summary[location][product]['count'] = count
summary[location][product]['date'] = countdate

This will remove the error.

There may be a more efficient way of doing this that I am not aware of, but I'm sure this works.

Upvotes: 2

Related Questions