0
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.

1
  • 1
    What 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. Commented Apr 14, 2015 at 23:05

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.