0

I have the following object data which looks like this:

data = {
          anna:{
                 phase1:23,
                 phase2:24,
                 phase3:0,
                 phase4:5,
                 phase5:0
               },
          Robin:{
                 phase1:16,
                 phase2:12,
                 phase3:21,
                 phase4:23,
                 phase5:2               
                }
        }

Now I wanted to convert them to where data variable is object and anna and robin is array of objects:

data = {
          anna:[
                 { phase1: 23 },
                 { phase2: 24 },
                 { phase3: 0 },
                 { phase4: 5 },
                 { phase5: 0 }
               ],
          Robin:[
                 { phase1: 16 },
                 { phase2: 12 },
                 { phase3: 21 },
                 { phase4: 23 },
                 { phase5: 2  }            
                ]
        }
A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76
Lee Lee
  • 565
  • 6
  • 14
  • 28

2 Answers2

1

A function like below might help you:

EDIT: edited the answer accommodating changes suggested by cafebabe1991.

function convertToArray(obj) {
 var retVal = [];

 for (var key in obj) { { //iterates through the list of key-val pairs
  if (obj.hasOwnProperty(key)) {
   retVal.push({ key: obj[key]});  //pushes it to newly created array
  }
 }
Varun Singh
  • 1,135
  • 13
  • 18
  • 1
    This is not the ideal way to loop through an object... use object.hasOwnProperty(key) so it does not iterate over the other properties. For further details read here .... http://stackoverflow.com/questions/684672/loop-through-javascript-object – cafebabe1991 Mar 19 '15 at 03:07
0

try this

function convertToArray(obj) {
 var retVal = [];
 for (key in obj) { //iterates through the list of key-val pairs
   if (obj.hasOwnProperty(key)) {
     retVal.push({ key: obj[key]});
   } //pushes it to newly created array
 }
 return retVal;
}
cafebabe1991
  • 4,928
  • 2
  • 34
  • 42