0

This is my Code

"type":{"0":   
        {   "label":"name",
    "required":false,
    "type":"String",
    },
    "1":
        {   "label":"email",
    "required":false,
    "type":"String",
    }
   }

In the above code I have Type object which contains two nested objects. Now I want to convert that object to array of objects in the following format using angularjs.

OutPut should be like this:-

"type":[
        {   "label":"name",
    "required":false,
    "type":"String",
    },
        {   "label":"email",
    "required":false,
    "type":"String",
    }
   ]
Charlie
  • 22,886
  • 11
  • 59
  • 90

7 Answers7

1

Something like this perhaps?

var arr = [];
Object.keys(obj).forEach(function(key)
{
    arr.push(obj[key]);
});
obj = { type: arr };
Tom Mettam
  • 2,903
  • 1
  • 27
  • 38
1

You could use the keys as index of the array.

var object = { "type": { "0": { "label": "name", "required": false, "type": "String", }, "1": { "label": "email", "required": false, "type": "String", } } },
    array = [];

Object.keys(object.type).map(function (k) {
    array[+k] = object.type[k];
});
object.type = array;
document.write('<pre>' + JSON.stringify(object, 0, 4) + '</pre>');
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

You should do this using Object.keys

objsArray = [];
Object.keys(objs).forEach(function(key)
{
    objsArray.push(objs[key]);
});
Charlie
  • 22,886
  • 11
  • 59
  • 90
0

say you have

var obj = {"type":{"0":   
        {   "label":"name",
    "required":false,
    "type":"String",
    },
    "1":
        {   "label":"email",
    "required":false,
    "type":"String",
    }
   }}

you can do

var arr = [];
for(var key in obj.type){
  arr.push(obj.type[key])
}
obj.type = arr;
Kishore Barik
  • 742
  • 3
  • 15
0

Let's say your object was:

var myObj = "type":{"0":   
        {   "label":"name",
    "required":false,
    "type":"String",
    },
    "1":
        {   "label":"email",
    "required":false,
    "type":"String",
    }
   };

If you're using Lodash library:

myObj.type = _.map(myObj.type)
Avinash
  • 812
  • 8
  • 17
0

For the sake of joining the party - better late than never. Working with arrays using functional programming is lots of fun and the accepted answer is great but a slight tweak and you got what is in my opinon much cleaner code.

 obj = { type: Object.keys(obj).map(function(key) { return obj[key]; }) };

or using a cleaner more sucinct ES6 steez

 obj = { type: Object.keys(obj).map(key => obj[key]) };

Super clean!

Sten Muchow
  • 6,623
  • 4
  • 36
  • 46
0

You can do it easily without loops:

// Assuming Problem: 
var objectToArray = 
{
"type":{"0": {"label":"name",
              "required":false,
              "type":"String",
             },
        "1": { "label":"email",
              "required":false,
               "type":"String",
             }
        }
    }

// Answer:
console.log( {type : Array.from(Object.values(objectToArray.type))} );
TrickOrTreat
  • 821
  • 1
  • 9
  • 23