0

I have the below javascript array with me

var test =[{
Maths:{
    ST1:10,
    ST2:2,
    ST3:15}
},
{
Science:{
    ST1:50,
    ST3:40}
    }
]

I want to generate the array shown below out of this

var t = [{ST1:{
               Maths:10,
               Science:50
              },
          ST2:{
               Maths:2,
               Science:0
              },
          ST3:{
               Maths:15,
               Science:40
              }
         }]

I tried using the code shown below

for (var key in test) {
  if (test.hasOwnProperty(key)) {
  for (var key1 in test[key]){
    //console.log(key1)}
    var abc = test[key][key1];
    for(var x in abc)
    {

    console.log(x+key1+abc[x])

    }

    }
  }
}

I am new to this help me doing this.

2
  • 1
    There's no JSON in your question. I think your use of that term is causing confusion. Commented Jun 7, 2012 at 18:52
  • Edit you post as post.replace('JSON', 'Object'); Commented Jun 7, 2012 at 18:53

4 Answers 4

1

This does mostly what you want...

var t = {};
for (var i = 0; i < test.length; i++) {
    for (var name in test[i]) {
        for (var level in test[i][name]) {
            if (!t[level])
                t[level] = {}
            t[level][name] = test[i][name][level]
        }
    }
}

Only thing missing is to get the Science:0 for when a STx value is missing under a section.

DEMO: http://jsfiddle.net/eHwBC/

Result:

{
    "ST1": {
        "Maths": 10,
        "Science": 50
    },
    "ST2": {
        "Maths": 2
    },
    "ST3": {
        "Maths": 15,
        "Science": 40
    }
}

Keep in mind that there's no guaranteed order when using for-in for enumeration.

If the labels (Math, Science, etc) are known in advance, then you can ensure that each object gets all labels.

If not, a separate loop can be done. Depending on the approach, it could be done before or after this main loop.

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

1 Comment

Oops... You wanted it wrapped in an Array. Add t = [t] to the end.
0

Do you know about JSON.stringify(t)?

It will convert an object literal to JSON.

Mozilla's documentation of this function is available at https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/JSON/stringify.

You can also read this blog article for further explanation

Comments

0

Try this:

var test =[{
Maths:{
    ST1:10,
    ST2:2,
    ST3:15
    }
},
{
Science:{
    ST1:50,
    ST3:40}
    }
];

var result = [];
for(i = 0; i <= test.length; i++){
  var resultRow = {};
  for(key in test[i]){
    for(subKey in test[i][key]){
      if(resultRow[subKey] == undefined){
        resultRow[subKey] = {};
      }
      resultRow[subKey][key] = test[i][key][subKey];
    }
  }
  result.push(resultRow);
}

Comments

0

Try like below,

/* Iterator start */
var t = {};
for (var i = 0; i < test.length; i++) {  //Iterate Maths, Science,..   
    for (var key in test[i]) {           //Iterate Math
        for (var iKey in test[i][key]) { //Iterate ST1, ST2, ST3
          var s = (t.hasOwnProperty(iKey))?t[iKey]:createObject();                    
          s[key] = test[i][key][iKey];
          t[iKey] = s;
        }
    }
}
/* Iterator End */ 

p = [];
p.push(t);
//^- p is what you want

// Separate function so you can add more items later without changing logic
function createObject () {
    return {'Maths' : 0, 'Science': 0};
}

DEMO and Proof below,

enter image description here

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.