我在对React中的对象列表进行排序时遇到了问题--按时间值是原生的。我在网上找不到答案。你有什么意见建议?
我的控制台登录原始对象的铬:

防火墙数据库结构

JSON.stringify(myObject)输出:
myObject={"-LAqmXKSdVVH6wirFa-g":
{"desc":"fdf","price":"rrrr","receiveHelp":true,"subject":"Single Variable
Calculus","time":1524558865757,"title":"Test1"},"-LAqmZlBFGoygfTsGQ0e":
{"desc":"dsfdsfd3","price":"333","receiveHelp":true,"subject":"Single
Variable Calculus","time":1524558875724,"title":"Test2"},"-
LAqmcipUjlwLWTrRCw4":
{"desc":"werwerwe55","price":"44","receiveHelp":true,"subject":"Single
Variable Calculus","time":1524558891956,"title":"Test3"},"-
LArMeYfHG6QMg_Frn9A":
{"desc":"3","price":"3","receiveHelp":true,"subject":"Single Variable
Calculus","time":1524568598762,"title":"Annons 1"},"-LArMjg5MkF5cMPZd_Fz":
{"desc":"2222","price":"2","receiveHelp":true,"subject":"Single Variable
Calculus","time":1524568619782,"title":"Annons2"},"-LArNM-3Ij60XmSOBwvr":
{"desc":"22","price":"","receiveHelp":true,"subject":"Single Variable
Calculus","time":1524568780803,"title":"Hej1"},"-LArNPugIfX1pPVZJ11e":
{"desc":"f","price":"2","receiveHelp":true,"subject":"Single Variable
Calculus","time":1524568796844,"title":"Hej2f"}}到目前为止,我已经尝试过:
firebase.database().ref('/users').once('value').then((snapshot) => {
const ads = snapshot.val();
let myObject = {};
Object.keys(ads).map((objectKey) => {
const value = ads[objectKey];
myObject = Object.assign(value.ads, myObject);
});
//Here i want to sort myObject by time and get the latest first
console.log(myObject)发布于 2018-04-24 14:42:01
您首先需要将广告或所有用户组合到一个数组中,然后进行排序。
let sortedAdds = Object.keys(usersData)
.reduce((prev, userId) => {
let ads = usersData[userId].ads;
ads = Object.keys(ads).map(key => {
return { ...ads[key], id: key };
});
return prev.concat(ads);
}, [])
.sort((a, b) => (a.time - b.time));
发布于 2018-04-24 14:36:49
([obj1, obj2]).sort((tm1, tm2) => {
if (tm1.time > tm2.time) {
return 1;
}
if (tm1.time < tm2.time) {
return -1;
}
return 0;
})发布于 2018-04-24 14:47:08
您可以使用Firebase数据库的排序功能,而不是在前端进行排序,方法是:
var ref = database.ref('users/' + adId + '/ads').orderByChild('time');如果您然后循环此查询的结果,广告将按时间排序。
ref.once('value', function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var childData = childSnapshot.val();
console.log(childData);
});
});编辑:如果你想拥有我理解为“最新的应该是第一次”的“最新的第一次”,那么你应该存储time*(-1)而不是time (time是unix时代以来的毫秒,如你的问题中所示)
https://stackoverflow.com/questions/50004286
复制相似问题