从json创建数组

时间:2017-06-29 10:07:45

标签: javascript arrays json

我在

下面收到了这个JSON
{
    "category": "test",
    "sealing_temp_1": "",
    "sealing_temp_2": "",
    "sealing_temp_3": "",
    "level_sensor_1": "",
    "level_sensor_2": "",
    "level_sensor_3": "",
    "check_pack_1": "",
    "check_pack_2": "",
    "check_pack_3": "",
    "comment": ""
}

我希望将其转换为此结构并保存

{
    "category": "test",
    "sealing_temp": "['a', 'b', 'c']",
    "level_sensor": "['x', 'y', 'z']",
    "check_pack": "[1, 2, 3]",
    "comment": ""
}

有人可以指导我,我尝试使用for..in但在此过程中迷失了

1 个答案:

答案 0 :(得分:2)

您可以拆分键,如果它的末尾有数字,则使用它来填充数组。

此提案更改了对象并删除了不需要的属性,这些属性现在是收集的数组中的值。



var object = { category: "test", sealing_temp_1: "s1", sealing_temp_2: "s2", sealing_temp_3: "s3", level_sensor_1: "l1", level_sensor_2: "l2", level_sensor_3: "l3", check_pack_1: "c1", check_pack_2: "c2", check_pack_3: "c3", comment: "cc" };
    
Object.keys(object).forEach(function (k) {
    var parts = k.split(/_(?=\d+$)/);
    if (parts.length === 2) {
        object[parts[0]] = object[parts[0]] || [];
        object[parts[0]][parts[1] - 1] = object[k]; // subtract one for zero based array
        delete object[k];
    }
});
console.log(object);

.as-console-wrapper { max-height: 100% !important; top: 0; }