0

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 
3
  • Did you define summary earlier by using var summary? Commented Nov 25, 2013 at 21:17
  • @echochamber Yes I did that. Commented Nov 25, 2013 at 21:20
  • Looks like ryguy has you covered. Commented Nov 25, 2013 at 21:23

3 Answers 3

2

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.

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

Comments

1

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'

Comments

1

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": {}}};

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.