Javascript: Converting Object of Objects to Array of Objects

萝らか妹 提交于 2019-12-07 19:01:38

问题


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' } } ];

回答1:


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.




回答2:


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"
   }
 ]



回答3:


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




回答4:


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"}}]"


来源:https://stackoverflow.com/questions/39360863/javascript-converting-object-of-objects-to-array-of-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!