javascript - Rewrite structure of a JSON Object -
javascript - Rewrite structure of a JSON Object -
i need create lot of json files project. json comes google spreadsheets. using data-drive json looks this:
{ "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" }
now want steps object itself. so:
{ "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"} ] }
here working solution:
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: [] }; (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]; } }
javascript json javascript-objects
Comments
Post a Comment