Javascript: Converting Object of Objects to Array of Objects

只谈情不闲聊 提交于 2019-12-06 13:24:39
abdulbarik

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.

I use this to convert mine

let arrayOfObjects = Object.keys(ObjectOfObjects).map(key => {
   let ar = ObjectOfObjects[key]

   // Apppend key if one exists (optional)
   ar.key = key

   return ar
})

In this case, your output would be

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

Can still optimize but this will get you your result.

var result = [];
for (var item in objectofobjects) {
  if (objectofobjects.hasOwnProperty(item)) {
    var key = item.toString();
    result.push({key: objectofobjects[item]});
  }
}
console.log(result);

The check inside is based on Iterate through object properties

objectofobjects = [objectofobjects]; // Simplest way to do this convertation.

JSON.stringify(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"}}]"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!