2016-09-07 288 views
2

我正在使用Polymer 1.0進行項目工作,我想使用dom-repeat來列出來自Firebase 3.0的數據。Javascript:將對象的對象轉換爲對象數組

在火力地堡我有這樣的對象的對象:

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

這第二個結構是無效的JSON。 http://jsonlint.com/ –

回答

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數組。

希望這應該工作。

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

+0

但這不是OP表示他想創建的格式。 – 2016-09-11 07:15:54

3

我用這個礦轉化

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