0

I have the following javascript object containing a multi-value email property:

var contact = {
    email =     {
        home =         (
            "me@home.com"
        );
        work =         (
            "me@work.com"
        );
    };
    emailCount = 2;
    firstName = Micah;
    lastName = Alcorn;
}

And I need to construct the following JSON to send to a Rails server:

processedContact.params = {
    'contact[first_name]':'Micah',
    'contact[last_name]':'Alcorn',
    'contact[emails_attributes][0][label]':'home',
    'contact[emails_attributes][0][account]':'me@home.com',
    'contact[emails_attributes][1][label]':'work',
    'contact[emails_attributes][1][account]':'me@work.com',
};

I don't know how to get past the following:

function processContact(contact) {
    processedContact = {};
    processedContact.params = {
        'contact[first_name]':contact.firstName,
        'contact[last_name]':contact.lastName,
        // ????????
    };
    for (each in contact.email) {
        // this can be used to produce the email.account values, but not the email.labels
    }
}

If I type this in statically, my Rails app handles it correctly. But let me know if there is a better was to handle it on the server side so that I don't have to manually construct the JSON. Thanks!

Micah Alcorn
  • 2,363
  • 2
  • 22
  • 45

1 Answers1

1

When I iterate through the contact.email I get labels. Getting the account is simply a matter of going back to the original contact Hash, thus:

function processContact(contact) {
    processedContact = {};
    processedContact.params = {
        'contact[first_name]':contact.firstName,
        'contact[last_name]':contact.lastName,
    };
    var index = 0;
    for (label in contact.email) {
        processedContact.params['contact[emails_attributes]['+index+'][label]'] = label;
        processedContact.params['contact[emails_attributes]['+index+'][account]'] = contact[label];
        index++;
    }
    return processedContact;
}
Sam Ruby
  • 4,270
  • 22
  • 21
  • In my particular use case, I had to change the last param to `processedContact.params['contact[emails_attributes]['+index+'][account]'] = contact.email[label].toString();`. Thanks so much! – Micah Alcorn Jul 09 '11 at 19:09