将具有方括号名称的JSON对象拆分为子对象

时间:2014-04-24 09:49:48

标签: javascript json forms

我们使用serializeObject对表单进行序列化,然后将其作为JSON编码字符串存储到本地存储中。当我们从LocalStorage中解码回来时,我们的密钥的名称为flight[inbound][0][iso]flight[outbound][1][date]等。这使得以后(在JavaScript中)很难正确循环,因为我们现在需要重新填充表格与存储的数据。

有没有办法将这些键名称进一步解码为子对象?例如:

flight[outbound][0][datetime] = "Something";
flight[outbound][0][from]     = "Something";
flight[outbound][0][to]       = "Something";
flight[outbound][0][carrier]  = "Something";
flight[inbound][0][datetime]  = "Something";
flight[inbound][0][from]      = "Something";
flight[inbound][0][to]        = "Something";
flight[inbound][0][carrier]   = "Something";

应该变成:

flight = {
    outbound: {
        0: {
            datetime: "Something",
            from:     "Something",
            to:       "Something",
            carrier:  "Something",
        }
    },
    inbound: {
        0: {
            datetime: "Something else",
            from:     "Something else",
            to:       "Something else",
            carrier:  "Something else",
        }
    }
}

1 个答案:

答案 0 :(得分:0)

事实证明我们使用的serializeObject插件没有做正确的工作。将其切换为https://github.com/macek/jquery-serialize-object,为我们提供了我们所追求的目标。