【问题标题】:Convert serialized() complex string to array of objects将 serialized() 复杂字符串转换为对象数组
【发布时间】:2019-05-29 17:02:55
【问题描述】:

我有一个字符串:

"id=1&lotcode=ACB&location=A1&id=2&lotcode=CCC&location=B1"

现在我想通过 ajax 获取一个对象数组以传递给控制器​​,如下所示:

[{"id":1, "lotcode"="ACB","location":"A1"},{"id":2, "lotcode"="CCC","location":"B1"}]

我从拆分字符串开始

var string = data.split('&', 2);

现在我卡在这里了……

【问题讨论】:

    标签: javascript json serialization


    【解决方案1】:

    您可以通过& 拆分字符串,然后获取键/值对并将它们分配给具有递增索引的数组。

    此解决方案假定所有键的计数相同。

    var string = "id=1&lotcode=ACB&location=A1&id=2&lotcode=CCC&location=B1",
        result = [],
        indices = {};
    
    string.split('&').forEach(s => {
        var [key, value] = s.split('='),
            index = (indices[key] || 0);
        
        result[index] = result[index] || {};
        result[index][key] = value;    
        indices[key] = index + 1;
    });
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-21
      • 1970-01-01
      • 2022-06-25
      • 2021-07-23
      • 1970-01-01
      相关资源
      最近更新 更多