对象的排序列表反应原生的值不是键

时间:2018-04-24 14:31:38

标签: javascript firebase react-native firebase-realtime-database jsx

我在使用时间值对React-native中的对象列表进行排序时遇到问题。我无法在线找到答案。你有什么建议吗?

我的控制台登录原始对象的chrome: My console log in chrome of original object

Firebase数据库结构

Firebase database structure

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)

3 个答案:

答案 0 :(得分:1)

read -r -d '' testConfig <<'EOF'
{
    "Classification": "mapred-site",
    "Properties": {
        "mapreduce.map.java.opts": "-Xmx2270m",
        "mapreduce.map.memory.mb": "9712"
      }
}
EOF

# Just to demonstrate that it works ...
echo "$testConfig" | jq .

答案 1 :(得分:0)

您首先需要将广告或所有用户合并到一个数组中然后排序

&#13;
&#13;
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));
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您可以执行以下操作,而不是在前端进行排序,使用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({{ 1}}是自unix时代以来的毫秒数,如你的问题所示)