-1

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.

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}
]
Luis Medina
  • 535
  • 3
  • 15
  • You cannot guarentee object key order. If you need to force an order, then either use an array, or keep a secondary array with the sorted order that you then use to access the properties in the required order. – Taplar May 18 '20 at 19:41
  • It doesn't since it is an alphabetical order – Luis Medina May 18 '20 at 19:43
  • 1
    Don't try to put properties in a certain order. It is an antipattern. Think of objects as an *unordered* set of properties. – trincot May 18 '20 at 19:44

1 Answers1

1

You should not attempt to put object properties in a specific order. Objects are better thought of as unordered collections of properties. 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.

Instead, change your inner data structure from plain objects to 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);
trincot
  • 317,000
  • 35
  • 244
  • 286