0

I got an object like this:

a = {
  CustomKey1: [
     {order: '2'},
     {order: '1'},
  ],
  CustomKey2: [
     {order: '2'},
     {order: '3'},
     {order: '1'},
  ],  
}

I need to sort based on the property "order" inside every object in every list.

I tried doing like this:

const result = Object.keys(a).map((customKey) => Object.keys(a[customKey]).map((key) => a[customKey][key]).sort((a, b) => a.order?.localeCompare(b.order)));

It works well, but in the result I lose the keys name, so I got:

total = {
  0: [
    {order: '1'},
    {order: '2'},
  ],
  1: [
    {order: '1'},
    {order: '2'},
    {order: '3'},
  ],
}

Is there a way to keep the original keys name? I need an object like this:

total = {
  CustomKey1: [
    {order: '1'},
    {order: '2'},
  ],
  CustomKey2: [
    {order: '1'},
    {order: '2'},
    {order: '3'},
  ],
}
samthecodingman
  • 23,122
  • 4
  • 30
  • 54
palnic
  • 386
  • 1
  • 4
  • 13

2 Answers2

1

First, your object keys have to be unique.

You can iterate over the Object.entries with reduce to build a new object.

const a = {
  CustomKey1: [
     {order: '2'},
     {order: '1'},
  ],
  CustomKey2: [
     {order: '2'},
     {order: '3'},
     {order: '1'},
  ]
};

const result = Object.entries(a).reduce((acc, [key, value]) => {
  return {
    ...acc,
    [key]: value.sort((a, b) => a.order.localeCompare(b.order))
  };
}, {});

console.log(result);
Andy
  • 61,948
  • 13
  • 68
  • 95
0

const a = {
  CustomKey1: [
     {order: '2'},
     {order: '1'},
  ],
  CustomKey2: [
     {order: '2'},
     {order: '3'},
     {order: '1'},
  ],  
};

const result = {};
for(const key in a){
  const values = a[key].slice(0);
  result[key] = values.sort((a, b) => a.order?.localeCompare(b.order));  
}

console.log("original", a);
console.log("sorted", result);

If the order values are guaranteed to be numeric, the sort should be changed to a numeric sort:

result[key] = values.sort((a, b) => Number(a.order) - Number(b.order));

This is because if you had an entry with { order: '10' }, it currently will be sorted before { order: '2' }. See this question for more information.

samthecodingman
  • 23,122
  • 4
  • 30
  • 54
GenericUser
  • 3,003
  • 1
  • 11
  • 17