Umfi Umfi - 7 months ago 64
Javascript Question

Cast object to array (key, value)

I have following object.

var data = { "A": 123, "B":456};

I want to cast this object to an array like this ["A":123, "B":456]

var a = new Array();
a['A'] = "123";
a['B'] = "456";

This does the job, but it return length 0.. so no correct array to iterate though.

Can anybody provide help?
I would need a solution without jQuery or JSON.parse() as it troughs exception in my angular controller.


["A":123, "B":456] is not a valid array in JS. In JS this is an object (your confusion may stem from other languages that call this an "associative array"). And is represented (and constructed) with curly braces like so: {A:123, B:456}, and there is no need to quote the keys

Objects do not a have length attribute like arrays BUT you can still loop though them like so:

var myObj = {"A":123, "B":456};
for( key in myObj ){
   var value = myObj[key];
    console.log(key + ': '+ value);