mayijia66fly mayijia66fly - 2 months ago 11
Node.js Question

Javascript: Converting Object of Objects to Array of Objects

I'm working on a project using Polymer 1.0 and I want to use

dom-repeat
to list data from Firebase 3.0.

In Firebase I have an object of objects like this:

var objectofobjects = {
"-KR1cJhKzg9uPKAplLKd" : {
"author" : "John J",
"body" : "vfdvd",
"time" : "September 6th 2016, 8:11",
"title" : "vfvfd"
},
"-KR1cLZnewbvo45fDnEf" : {
"author" : "JJ",
"body" : "vfdvdvf",
"time" : "September 6th 2016, 8:11",
"title" : "vfvfdvfdv"
}
};


and I want to convert it to an array of objects like this:

var arrayofobjects = [
"-KR1cJhKzg9uPKAplLKd" : {
"author" : "John J",
"body" : "vfdvd",
"time" : "September 6th 2016, 8:11",
"title" : "vfvfd"
},
"-KR1cLZnewbvo45fDnEf" : {
"author" : "JJ",
"body" : "vfdvdvf",
"time" : "September 6th 2016, 8:11",
"title" : "vfvfdvfdv"
}
];

Answer

You can do it in this simple way:

 var arrObj=[];

 var obj=JSON.stringify(objectofobjects,function(key,value){

      arrObj.push(value);
  })
   console.log(arrObj);

And the output will be this:

[ { '-KR1cJhKzg9uPKAplLKd': 
     { author: 'John J',
       body: 'vfdvd',
       time: 'September 6th 2016, 8:11',
       title: 'vfvfd' },
    '-KR1cLZnewbvo45fDnEf': 
     { author: 'JJ',
       body: 'vfdvdvf',
       time: 'September 6th 2016, 8:11',
       title: 'vfvfdvfdv' } } ]

Note: The output which you have mentioned is not a valid JSON array.

Hope this should work.