javascript - How to convert a nested object into an array of objects? -
inputjson = { "mn": { "mt1": 1, "mtop": 2, "ot1": 3 }, "ln": { "mt1": 4, "mtop": 5, "ot1": 6 } } outputarrayofjson=[ { rs: "mt1", mn: 1, ln: 4 }, { rs: "mtop", mn: 2, ln: 5 }, { rs: "ot1", mn: 3, ln: 6 } ]
- rs hardcode key.
i don't know why having hard time doing operation.
it conversion of javascript objects
inputjson = { "mn": { "mt1": 1, "mtop": 2, "ot1": 3 }, "ln": { "mt1": 4, "mtop": 5, "ot1": 6 } } d = {}; for(var key1 in inputjson){ for(var key2 in inputjson[key1]) { if(!(key2 in d)){ d[key2]={}; } d[key2][key1] = inputjson[key1][key2]; } } v = []; for(var k in d){ var o = {}; o.rs=k; for(var k2 in d[k]){ o[k2] = d[k][k2]; } v.push(o); } //result in v
note: next time should shown example code or not help
Comments
Post a Comment