2

I'm struggling to understand what I'm doing wrong here.

I have an empty object:

if ( doc._attachments === undefined ){
    doc._attachments = {};
}
var attmtid = 123;

which I'm trying to populate like so:

doc._attachments[attmtid].revpos = "abc";

However I keep getting an undefined error from Firebug:

doc._attachments[attmtid] is undefined

And can't really make any sense of it.

Question:
Can someone tell me what I'm doing wrong?

Thanks!

3 Answers 3

6

Why not do:

doc._attachments[attmtid] = {
    revpos: "abc"
};
Sign up to request clarification or add additional context in comments.

Comments

5

doc._attachments[attmtid] is undefined, which means you need to define it as something. An array, an object, a string, etc. For example, you could make it another object:

doc._attachments[attmtid] = {};

And then be able to set properties on that object:

doc._attachments[attmtid].revpos = "abc";

3 Comments

Ok. I got it. I guess I need to define both _doc.attachments and _doc.attachments[123] which makes sense since I need to keep track of different attachments to a single document.
@frequent You probably want to do the same undefined check for _doc.attachments[attmtid] before initializing, so you don't overwrite other properties.
@frequent - Yup, you got it. You can't go around setting properties on an undefined object. For example: var x = {}; x.y.z = 1; isn't going to work.
2

doc._attachments[attmtid] is not initialized to an object so you cannot dynamically assign the revpos property.

This should resolve it:

doc._attachments[attmtid] = {};
doc._attachments[attmtid].revpos = "abc";

Note: This is based on the expectation that you want a doc._attachments.123 property (which is what the example code in the question would create) and not a doc._attachments.attmid property.

1 Comment

Probably want to check if doc._attachments[attmtid] is undefined first - only if it is, then initialize it with {}. Then always set the revpos property.

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.