Javascript:将对象的对象转换为对象数组

我正在使用Polymer 1.0开发一个项目,我想使用dom-repeat从Firebase 3.0中列出数据。

在Firebase中,我有这样的对象的对象:

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

我想将它转换为这样的对象数组:

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

你可以用这个简单的方法来做到这一点:

  var arrObj = []; var obj = JSON.stringify(objectofobjects, function(key, value) { arrObj.push(value); }) console.log(arrObj); 

output将是这样的:

 [{ '-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' } }] 

注意 :您提到的输出不是有效的JSON数组。

希望这应该工作。

我用这个来转换我的

 let arrayOfObjects = Object.keys(ObjectOfObjects).map(key => { let ar = ObjectOfObjects[key] // Apppend key if one exists (optional) ar.key = key return ar }) 

在这种情况下,你的输出是

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

仍然可以优化,但这会得到你的结果。

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

里面的检查是基于遍历对象属性

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