简体   繁体   English

Javascript 对 object 值进行排序

[英]Javascript sorts object values

Hope you have been a good day.希望你过得愉快。 I want to ask you a question.我想问你一个问题。 Here is it:就这个:

So I have an object and I get values from it with Underscore.js (I will give you an example without using underscore.js to getting values).所以我有一个 object 并使用 Underscore.js 从中获取值(我会给你一个例子,而不使用 underscore.js 来获取值)。

After I get values, it puts numbers that are bigger than 0. I think it sorts bigger than smaller.在我得到值之后,它会放置大于 0 的数字。我认为它的排序大于小于。

I want values exactly how they are at the object before I take them .在我接受它们之前,我想要它们在 object 上的确切值

Here is an image for you这是给你的图像

在此处输入图像描述

Here is the code这是代码

tmpReport.forEach(element => {
            const tmpVal = [];
            console.log("element: ", element);
            tmpValList.push(_.values(element));
            console.log('tmpValList: ', tmpValList);
        });

Here is the code without using underscore.js:这是不使用 underscore.js 的代码:

tmpReport.forEach(element => {
            const tmpVal = [];
            console.log("element: ", element);
            Object.entries(element).forEach(([key, value]) => {
                tmpVal.push(value);
            });
            tmpValList.push(tmpVal);
            console.log('tmpValList: ', tmpValList);
        });

So any help will be appreciated.因此,任何帮助将不胜感激。 Thank you!谢谢!

In JavaScript, the order of object entries is not guaranteed.在 JavaScript 中,不保证 object 条目的顺序。 If you want to put specific entries at specific indices in your array you have to do that manually.如果要将特定条目放在数组中的特定索引处,则必须手动执行此操作。

For example:例如:

tmpVal[0] = element['Cell damage by placing'];
...
tmpVal[4] = element['time'];
tmpVal[5] = element['toplan'];

You can only achieve that if you are aware of your object keys.如果您知道您的 object 密钥,您只能实现这一点。 As far as I know there is now generic way to keep the initial order as there is no order to begin with.据我所知,现在有一种通用的方法来保持初始顺序,因为没有顺序开始。

The best you can do in that case is use a lexicographic order and sort your keys accordingly.在这种情况下,您可以做的最好的事情是使用字典顺序并相应地对您的键进行排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM