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}
]

5
  • 1
    You may find this helpful stackoverflow.com/questions/1069666/…. Also check comment from @Govind Rai on that question. Commented Apr 27, 2021 at 8:05
  • 3
    Why do you need it? The order of the keys should not matter. Commented Apr 27, 2021 at 8: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. Commented Apr 27, 2021 at 8: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, 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). Commented Apr 27, 2021 at 8:39
  • w3docs.com/snippets/javascript/… Commented Apr 27, 2021 at 8:42

1 Answer 1

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.