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

时间:2016-09-07 03:39:55

标签: javascript arrays node.js polymer firebase-realtime-database

我正在使用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' } } ];

4 个答案:

答案 0 :(得分:5)

我用它来转换我的

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

答案 1 :(得分:1)

仍然可以进行优化,但这样可以获得结果。

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

内部检查基于Iterate through object properties

答案 2 :(得分:1)

  

你可以用这种简单的方式做到:

 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数组。

希望这应该有用。

答案 3 :(得分:0)

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"}}]"
相关问题