0

I have array of objects which are not alphbatically sorted. I want to sort these key names. Is there any way to do this?

const artists = [
    {name: "Tupac", year: 1996, age: 25},
    {name: "Jayz",  year: 2021, age: 48}
]
// Looking for Output like this

const artists = [
    {age: 25, name: "Tupac", year: 1996},
    {age: 48, name: "Jayz",  year: 2021}
]
  • 1
    You may find this helpful https://stackoverflow.com/questions/1069666/sorting-object-property-by-values. Also check comment from @Govind Rai on that question. – Karan Apr 27 '21 at 08:05
  • 3
    Why do you need it? The order of the keys should not matter. – Bronislav Růžička Apr 27 '21 at 08:08
  • I want them in specific order because the key values in my data are not in exact order in every object and i want to remove some of key values in VS code at one time. – gothamdarkknight Apr 27 '21 at 08:26
  • It's still not clear why the properties should be in a specific order. The iterating order of the keys is defined in [some cases](https://stackoverflow.com/a/30919039/1169519), but you can't specifically sort objects. If you need to iterate objects in a specific order, you've to implement your own iterating method (which is actually not as difficult as it might sound). – Teemu Apr 27 '21 at 08:39
  • https://www.w3docs.com/snippets/javascript/how-to-sort-javascript-object-by-key.html – Mike de Bie Apr 27 '21 at 08:42

1 Answers1

1

The following might work in practice. But there are caveats. If you absolutely need to guarantee the order I believe the advice is to use Map or convert to an array.

const artists = [
    {name: "Tupac", year: 1996, age: 25},
    {name: "Jayz",  year: 2021, age: 48}
];

const sort_object_keys = (object) =>
  Object.keys(object)
    .sort()
    .reduce(
      (acc, val) => Object.assign(acc, { [val]: object[val] }),
      {}
    );

const result = artists.map(sort_object_keys);

console.log(result);
Ben Stephens
  • 1,663
  • 2
  • 5