2016-09-07 253 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"}}]"