为Rails构造多值JSON

时间:2021-01-29 08:22:12

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

我有以下包含多值电子邮件属性的javascript对象:

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:

我需要构造以下JSON以发送到Rails服务器:

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!

如果我静态输入,我的Rails应用程序正确处理它。但是让我知道是否有更好的方法在服务器端处理它,这样我就不必手动构建JSON。谢谢!

1 个解决方案

#1


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:

当我遍历contact.email时,我得到了标签。获取帐户只需返回原始联系人Hash,因此:

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

#1


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:

当我遍历contact.email时,我得到了标签。获取帐户只需返回原始联系人Hash,因此:

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