重写JSON对象的结构

Ram*_*ben -1 javascript json javascript-objects

我需要为项目制作大量的JSON文件.此JSON来自Google Spreadsheets.使用数据驱动器我得到如下所示的JSON:

{
  "custom_id": 1,
  "another_thing": "pizza",
  "step_1_message": "msg",
  "step_1_hint": "hint",
  "step_1_intent": "intent",
  "step_2_message": "msg",
  "step_2_hint": "hint",
  "step_2_intent": "intent"
}
Run Code Online (Sandbox Code Playgroud)

现在我希望所有步骤都来自一个对象.像这样:

{
  "custom_id": 1,
  "another_thing": "pizza",
  "steps": [
   {"step_id": 1, "message": "msg", hint: "hint", "intent": "intent"},
   {"step_id": 2, "message": "msg", hint: "hint", "intent": "intent"}
  ]
}
Run Code Online (Sandbox Code Playgroud)

jcu*_*bic 6

这是工作解决方案:

var input = {
  "custom_id": 1,
  "another_thing": "pizza",
  "step_1_message": "msg",
  "step_1_hint": "hint",
  "step_1_intent": "intent",
  "step_2_message": "msg",
  "step_2_hint": "hint",
  "step_2_intent": "intent"
};
var output = {
    steps: []
};
for (var key in input) {
    var m = key.match(/step_([0-9]+)_(\w+)/);
    if (m) {
        var num = m[1];
        var name = m[2];
        if (!output.steps[num-1]) {
            output.steps[num-1] = {
                step_id: num
            };
        }
        output.steps[num-1][name] = input[key];
    } else {
        output[key] = input[key];
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 根据需要插入step_id需要进行轻微修改```if(!output.steps [num-1]){output.steps [num-1] = {}; ````应该是```if(!output.steps [num-1]){output.steps [num-1] = {}; output.steps [num-1] .step_id = num; }``` (2认同)