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 is hardcode Key.
I don't know why am having hard time doing this operation.
Felix Kling
820k181 gold badges1.1k silver badges1.2k bronze badges
asked Apr 14, 2015 at 22:24
Rajul
1861 gold badge3 silver badges14 bronze badges
-
1What you have is not JSON. JSON is a language-independent, textual data format, just like XML or CSV. You simply have a JavaScript object and want to convert it to an array.Felix Kling– Felix Kling2015年04月14日 23:05:55 +00:00Commented Apr 14, 2015 at 23:05
2 Answers 2
It is a 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 is in v
note: the next time you should shown example code or not will help
answered Apr 14, 2015 at 23:23
Jose Ricardo Bustos M.
8,1847 gold badges44 silver badges66 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
You can iterate through the object and push each root property inside an array:
var arr = [];
for (var p in inputJson){
arr.push(inputJson[p]);
}
console.log(arr);
answered Apr 14, 2015 at 22:57
ianaya89
4,2613 gold badges29 silver badges34 bronze badges
Comments
lang-js