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' } } ];
abdulbarik
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.
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"
}
]
g3ctong
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
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