我正在尝试对对象进行排序,然后使用已排序的数据创建一个新对象。但问题是,每当我将数据推送到空数组时,它就会创建一个父对象为0,1,2的新对象......
{
"0": {
"note-1502256197947": {
"content": "If that doesn't work, then it will reload the entire page.",
"fav": true,
"last_modified": "",
"publish_date": 1502256197947,
"slug": "starred-note",
"title": "Starred Note"
}
},
"1": {
"note-1502108241905": {
"categories": {
"Learn": true,
"Wordpress": true
},
"content": "Creating a embed several routes to handle Creation, Retrieval",
"fav": true,
"last_modified": "",
"publish_date": 1502108241905,
"slug": "a-new-title",
"title": "A New Title"
}
}
}
以下是我尝试对对象进行排序的方法:
var noteref = firebase.database().ref(`noted${uid}/notes/`);
var sortedKeys = [];
noteref.orderByChild('fav').once("value", function(snapshot) {
snapshot.forEach(function(child) {
sortedKeys.unshift({[child.key]:child.val()});
//sortedKeys[child.key] = child.val(); ***Works! but the order is lost
});
var newObject = {...sortedKeys};
console.log(newObject);
});
这是我尝试重新创建对象的方法:
{
"note-1502256197947": {
"content": "If that doesn't work, then it will reload the entire page.",
"fav": true,
"last_modified": "",
"publish_date": 1502256197947,
"slug": "starred-note",
"title": "Starred Note"
},
"note-1502108241905": {
"categories": {
"Learn": true,
"Wordpress": true
},
"content": "Creating a embed several routes to handle Creation, Retrieval",
"fav": true,
"last_modified": "",
"publish_date": 1502108241905,
"slug": "a-new-title",
"title": "A New Title"
}
}
答案 0 :(得分:0)
我认为你缺少一些对象的概念。如果一个对象有几个属性,那么它并不意味着它以任何方式排序。
{
"note-1502256197947": {...
},
"note-1502108241905": {...
}
}
假设这是一个对象。此对象有2个属性 note-1502256197947 和 note-1502108241905 。这并不意味着它们已被分类。
答案 1 :(得分:-1)
如果你想要对象格式的数据意味着为什么要将值推入数组? 然后在foreach中制作格式之前更好的事情,
可能有两种格式化方式: 1.创建一个空对象并按预期生成格式,如下所示: snapshot.forEach(function(child){
sortedKeys[child.key] = child.val();
});
2。正如你现在关注的那样
注意:通过调试确保来自api和foreach内部的数据是否正在进行