john smith
john smith

Reputation: 561

javascript object of object editing

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?

Upvotes: 1

Views: 99

Answers (4)

LetterEh
LetterEh

Reputation: 26696

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

Upvotes: 0

ATOzTOA
ATOzTOA

Reputation: 35940

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
}

Upvotes: 3

dfsq
dfsq

Reputation: 193251

Maybe the shortest possible way:

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

Upvotes: 0

sdespont
sdespont

Reputation: 14025

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

Upvotes: 0

Related Questions