简体   繁体   English

Javascript object 固定按键排序

[英]Javascript object fixed sort by key

I want to give a fixed order to an array of javascript objects and I've trying with the answer of this post but they are pointing to the value, not the keys.我想给一个 javascript 对象数组一个固定的顺序,我已经尝试了这篇文章的答案,但它们指向的是值,而不是键。

fixed_order = ['group','A,'N','R']

data=[
{group: "a", A: 8, N: 6}
{group: "b", N: 4, A: 20, R: 1}
{group: "c", A: 7}
]

I've try with something like this but doesn't work.我尝试过这样的事情,但没有用。

data.sort(function (a, b) {
    return fixed_order.indexOf(a.keys()) - fixed_order.indexOf(b.keys());
});

the result shoulb be something like this:结果应该是这样的:

data=[
{group: "a", A: 8, N: 6}
{group: "b", A: 20, N: 4, R: 1}
{group: "c", A: 7}
]

You should not attempt to put object properties in a specific order.您不应尝试按特定顺序放置 object 属性。 Objects are better thought of as unordered collections of properties.对象最好被认为是无序的 collections 属性。 Even though modern engines implement the order defined by recent EcmaScript specifications, it is not considered good practice to make your code rely on that.尽管现代引擎实现了最近的 EcmaScript 规范定义的顺序,但让你的代码依赖它并不是一种好的做法。

Instead, change your inner data structure from plain objects to arrays.相反,将您的内部数据结构从普通对象更改为 arrays。 An array is the recommended data structure when order is important.当顺序很重要时,数组是推荐的数据结构。

 const fixedOrder = ['group', 'A', 'N', 'R']; const data = [ [["group", "a"], ["A", 8], ["N", 6]], [["group", "b"], ["N", 4], ["A", 20], ["R", 1]], [["A", 7], ["group", "c"]] ]; for (const row of data) { row.sort((a, b) => fixedOrder.indexOf(a[0]) - fixedOrder.indexOf(b[0])); } console.log(data);

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

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