热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

使用react和firebase对对象javascript进行排序-Sortingobjectsjavascriptwithreactandfirebase

IamdoingaprojectusingreactandIcannotsortthevaluesofseveralobjects.我正在使用react做一个项目,我

I am doing a project using react and I can not sort the values of several objects.

我正在使用react做一个项目,我无法对几个对象的值进行排序。

In fact, here is the structure of my objects:

实际上,这是我的对象的结构:

object1:
   subobject1
      hours: "06",
      details:"lorem ipsum",
   subobject2
      hours: "04",
      details:"lorem ipsum",
object2:
   subobject1
      hours: "05",
      details:"lorem ipsum",
   subobject2
      hours: "01",
      details:"lorem ipsum",

All recovered objects are in this same form.

所有恢复的对象都采用相同的形式。

I would like to display these objects by sorting on the "hours" property and return an object like this :

我想通过对“hours”属性进行排序来显示这些对象,并返回如下对象:

   object1:
   subobject1
      hours: "04",
      details:"lorem ipsum",
   subobject2
      hours: "06",
      details:"lorem ipsum",
object2:
   subobject1
      hours: "01",
      details:"lorem ipsum",
   subobject2
      hours: "05",
      details:"lorem ipsum",

Can you help me please ?

你能帮我吗 ?

Thanks for any help

谢谢你的帮助

Edit : sorry, I was wrong about the structure

编辑:对不起,我错了结构

3 个解决方案

#1


1  

You can use lodash for such a simple functionality https://lodash.com/docs/4.17.5#sortBy

你可以使用lodash这样一个简单的功能https://lodash.com/docs/4.17.5#sortBy

import _ from 'lodash'

objects = [{hours: 1}, {hours: 3}]
sortedObject = _.sortBy(objects, 'hours')

#2


1  

Let say data is an array containing all those objects then

假设数据是包含所有这些对象的数组

Ascending

var sortedData = data.sort((a, b) => Number(a.hours) - Number(b.hours));

Descending

var sortedData = data.sort((a, b) => Number(b.hours) - Number(a.hours));

#3


0  

I'm making the assumption you are working with an array of objects. If so, this can be simply done with

我假设您正在使用一组对象。如果是这样,可以简单地完成

ArrayOfObjects.sort(function(a, b) { return (+a.hours) - (+b.hours) });

Or es6

ArrayOfObjects.sort((a, b) => (+a.hours) - (+b.hours));

推荐阅读
author-avatar
手机用户2502863161
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有