dk123
dk123

Reputation: 19680

Javascript turning object map into Array

Say for example I had an object map of the following:

{
    "key1" : { data: "data1", extra: "none" },
    "key2" : { data: "data2", extra: "none" },
    "key3" : { data: "data3", extra: "none" },
    "key4" : { data: "data4", extra: "none" }, 
};

Is there a convenient way to convert it to an array something like this:

[
    { "key1" : { data: "data1", extra: "none" }},
    { "key2" : { data: "data2", extra: "none" }},
    { "key3" : { data: "data3", extra: "none" }},
    { "key4" : { data: "data4", extra: "none" }}, 
];

I have a function that requires an array, yet the data I'm receiving from a 3rd party plugin is in object arrays. It would be nice if there was some simple way to get the conversion done between the two.

Upvotes: 1

Views: 171

Answers (2)

HBP
HBP

Reputation: 16033

More succinctly (in ECMAscript 5):

function toArray (obj) {
  return Object.keys (obj).map (function (k) {
    var v = {}; v[k] = obj[k]; return v; 
  });
}

Upvotes: 1

Asad Saeeduddin
Asad Saeeduddin

Reputation: 46628

Iterate over the properties in your object and push them to an array:

var myArray=[];
for (k in myObj) {
    if(myObj.hasOwnProperty(k)){
        var newObj = {};
        newObj[k] = myObj[k];
        myArray.push(newObj);
    }
}

Upvotes: 3

Related Questions