【问题标题】:How to sort with map by value in JavaScript如何在 JavaScript 中按值对地图进行排序
【发布时间】:2020-09-13 07:43:13
【问题描述】:

嘿,我正在学习如何使用 JS 和 firebase。我的问题是我的订单是随机加载的,我总是希望它按时间排序。我已经尝试对来自 firebase 的数据进行排序,但它仍然是随机出现的。

我看过一些关于对我的地图进行排序的事情,称为“行”,但似乎无法以任何合理的方式实现它。

这就是我尝试在我的订单页面获取之前对我的 firebase 数据库进行排序的方式

// route for database 
router.get("/orderslist", (req, res) => {    

  let orders = []
  let number_of_orders

    // Getting the snapshot of the order collection
    db.collection('orders').orderBy('time').get().then( productSnapshot => {
      number_of_orders = productSnapshot.size

      // iterating over the order snapshot
      productSnapshot.forEach(orderDoc => {

        // creating an order object and assigning the ID and the rest of the information from the database
        var order = {
          id: orderDoc.id,
          customer_name: orderDoc.data().customer_name,
          date: orderDoc.data().date,
          comments: orderDoc.data().comments,
          time: orderDoc.data().time,
          total: orderDoc.data().total,
          order_status: orderDoc.data().order_status,
          products: []
        }
        // using the id, to get the products from the subcollection
        db.collection('orders/' + order.id + '/products').get().then( productSnapshot => {

          // iterating over the product snapshot
          productSnapshot.forEach(productDoc => {

            // creating a product object
            var product = {
              name: productDoc.data().name,
              price: productDoc.data().price
            }

            // then we push the product object to the list of products in the order object
            order.products.push(product)

          });

          // we are finished iterating over the productsnapshot and now we can push it to the orders list
          orders.push(order)

          // checks if the list is filled with everything from the database
          if(orders.length == number_of_orders){
            return res.json(orders)
          }

        });

      });

  });

});

这是我的 json 输入

[
  {
    "id": "s2hym8IVa10pEgtgmmq9",
    "customer_name": "Mikkel",
    "date": "13/05-2020",
    "comments": "",
    "time": 1050,
    "total": 40,
    "order_status": true,
    "products": [
      {
        "name": "Latte",
        "price": 40
      }
    ]
  },
  {
    "id": "xWmlB9fHD4rw8Di75llp",
    "customer_name": "Emil",
    "date": "07/05-2020",
    "comments": "without sugar",
    "time": 1211,
    "total": 40,
    "order_status": false,
    "products": [
      {
        "name": "Latte",
        "price": 40
      }
    ]
  },
  {
    "id": "ggYSVKA1i0U8khIpeud4",
    "customer_name": "Oliver",
    "date": "01/05-2020",
    "comments": "order to be packed neatly because im on a bike",
    "time": 1450,
    "total": 38,
    "order_status": false,
    "products": [
      {
        "name": "Latte Macchiato",
        "price": 38
      }
    ]
  },
  {
    "id": "pq62yo42KS41VgeGGiZX",
    "customer_name": "Naida",
    "date": "07/05-2020",
    "comments": "nope",
    "time": 1257,
    "total": 40,
    "order_status": true,
    "products": [
      {
        "name": "Latte",
        "price": 40
      }
    ]
  },
  {
    "id": "p2dKspiU535P29Gex6Uz",
    "customer_name": "Alper",
    "date": "13/05-2020",
    "comments": "",
    "time": 1937,
    "total": 40,
    "order_status": false,
    "products": [
      {
        "name": "Latte",
        "price": 40
      }
    ]
  }
]

这是我的订单页面 JS

  // jquery getting our json order data from API
    $.get("http://localhost:8888/orderslist", (data) => {    


        // loops through our orderlist api
        let rows = data.map(item => {
          let $clone = $('#frontpage_new_ordertable tfoot tr').clone();
          $clone.data("id", item.id);
          $clone.find('.customer_name').text(item.customer_name);
          $clone.find('.date').text(item.date);
          $clone.find('.time').text(item.time);
          $clone.find('.pickup').text(item.pickup);
          $clone.find('.comments').text(item.comments);
          $clone.find('.total').text(item.total + ' Kr.');


          // accept and cancel buttons
          $clone.find('.order_status').html(
            `<button class="acceptOrder" type="button">Accept</button>` + 
            `<button class="cancelOrder" type="button">Cancel</button>`
          );

          // loops through orders product name
          let productsName = item.products.map(prod => `${prod.name}`);
          $clone.find('.products').html(productsName.join('<br />'));

          // loops through orders product price
          let productsPrice = item.products.map(prod => `${prod.price} Kr.`);
          $clone.find('.price').html(productsPrice.join('<br />'));

          return $clone;
        });


        //appends to our frontpage html 
        $("#frontpage_new_ordertable tbody").append(rows);
    });

});

【问题讨论】:

  • 您只显示一个对象。为了对某些东西进行排序,我期望有一个对象数组。能否请您包含从 firebase 获得的数据?
  • “我已经尝试从 firebase 的数据中进行排序,但仍然没有成功。” 请告诉我们。问题中的代码中没有任何内容正在排序或似乎试图对任何内容进行排序。
  • 可能在这里回答:stackoverflow.com/questions/979256/…
  • @T.J.Crowder 添加了 firebase js 和我的其余 json 数据
  • 如果我没记错的话,Firebase 本身就提供了排序,甚至在它到达对象数组之前。事实上,您在检索orders 时已经收到了.orderBy('time') 调用。如果您想对产品进行分类,只需在get() 调用之前添加.orderBy('property')。或者不管它如何工作;我不是 Firebase 专家。但我希望在 Firebase 中对其进行本地排序会更快,或者至少与事后排序一样快。

标签: javascript jquery json firebase sorting


【解决方案1】:

你可以试试这个

const rows = [{time: 1}, {time: 1050}, {time: 238}, {time: 9999}]

//sorted result
rows.sort((a,b) => a.time - b.time)

【讨论】:

  • 按对象属性对对象数组进行排序是一个非常常见的重复问题,并且在许多以前的形式中都有答案,例如@ 987654321@(正如我在评论中提到的那样)。请不要发布明显重复的答案。
【解决方案2】:

我相信这就是你要找的东西:data.sort

例如。 (排序功能)

data.sort((a,b)=>{
  return (a.date > b.date)
})

这仅在 item.date 是 Date 对象时才有效。

要创建日期对象,您可以使用: new Date(item.date)

PS。 你可以用&lt;翻转这个&gt;标志来改变顺序

【讨论】:

  • 按对象属性对对象数组进行排序是一个非常常见的重复问题,并且在许多以前的形式中都有答案,例如@ 987654321@(正如我在评论中提到的那样)。请不要发布明显重复的答案。
猜你喜欢
  • 2016-10-25
  • 2022-01-06
  • 2012-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-16
  • 1970-01-01
相关资源
最近更新 更多