开发者

Constructing multi-value JSON for Rails

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_na开发者_如何学运维me]':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!


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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜