1

I have the following code, which doesn't work.

var conversations = { };
conversations['5634576'].name = 'frank';

Apparently I cannot create objects inside objects. I wanted to use the conversation object to store arrays of objects to keep a history of messages client-side with localStorage to save space server side.

But apparently, I cannot even create variables inside the object, unless they already exist, like this:

var conversations = { 123: { name: 'test' } };
conversations[123].name = "frank";

But, since I will not know the IDs that will be used, I have no idea how workaround this problem.

Any ideas?

5
  • 1
    var conversations = {}; conversations['5634576'] = {}; conversations['5634576'].name = 'frank';, you can check if the second step is necessary using if (!conversations.hasOwnProperty('5634576')) { /*..*/ } Commented Feb 23, 2013 at 17:51
  • what a hassle.... well, thanks anyway! Commented Feb 23, 2013 at 17:51
  • Or var conversations = { }; conversations['5634576'] = {name: 'frank'}. "what a hassle.": well, what do you expect? You are trying to access the value at property '5634576', which does not exist. Please read MDN - Working with Objects. Commented Feb 23, 2013 at 17:52
  • but, when the user receives a new message, the object is re-created, therefore rewriting it, with the string example you cannot see it but, imagine it being an array: it will be a problem. Commented Feb 23, 2013 at 17:56
  • @john: Only initialize the object/array/whatever if it does not exist yet. Commented Feb 23, 2013 at 17:58

4 Answers 4

3

You need to do like this:

// Create an object
var conversations = {};

// Add a blank object to the object if doesn't already exist
if (!conversations.hasOwnProperty('5634576')) {
    conversations['5634576'] = {};
}

// Add data to the child object
conversations['5634576'].name = 'frank';

The object will look like this:

conversations{
    '5634576': {
        name : 'frank'
    }
}

Update

You can check if the element exist using in

if('5634576' in conversations) {
    // Exist
}
Sign up to request clarification or add additional context in comments.

4 Comments

what about arrays? if i instantiate the array like this -> conversations['5634576'].messages = []; conversations['5634576'].messages.push(message); i will lose the previous messages. can I prevent this?
conversations['5634576'] = conversations['5634576'] || {}; conversations['5634576'].messages = conversations['5634576'].messages || [];
@john: Only do conversations['5634576'].messages = []; when .messages does not exit yet. Obviously you will loose any previous value when you assign a new value.
@johnsmith If you do push, you won't lose previous messages.
0

In your code, you can't add a variable to the index '5634576' because it is not still existing.

var conversations = { };
conversations['5634576'].name = 'frank';

You need to create it, then assign the valriable

var conversations = { };
conversations['5634576'] = {};
conversations.name = 'frank';

Comments

0

Maybe the shortest possible way:

var conversations = {};
(conversations['5634576'] = {}).name = 'frank';

Comments

0
// build this how you were
conversations = {};

// if conversations[12345] is defined, use it:
// else set it to an object with the desired properties/methods
conversations["12345"] = conversations["12345"] || { name : "Frank", messages : [] };
conversations["12345"].messages.push(new_msg);

I'm assuming you're going to be doing this within a function, XHR or otherwise

conversations.add_message = function (msg) {
    var id = msg.conversation_id;
    conversations[id] = conversations[id] ||
                        conversations.new_conversation(msg.user_name); // returning a conversation object
    conversations[id].messages.push(msg);
};


conversations.new_conversation = function (name) {
    return { name : name, messages : [], etc : {} };
};

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.