js object, sort strings by keys, random order

I have for example the following json object.

let obj = [{
 amount: 0
 description: "something"
 latinName: "something else"
 location: "blabla"
 number: 0
 size: "something something"
 price: "something bla"
},
{...}
]

And I need to sort the keys into e.g.

[{ 
 number: 0, 
 latinName: 'something else', 
 location: "blabla", 
 description: "something", 
 size: "something something", 
 price: "something bla",
 amount: 0
},
{...}
]

How would I go about that? If I dont want to sort them by value or alphabet. I couldn’t find anything useful on the web regarding an lets call it sort by personal preference.

64 thoughts on “js object, sort strings by keys, random order”

  1. Objects cannot be sorted, they’re just a key-value combination. If you wanted to sort pairs like this, you’d need to use an array of arrays:

    let obj = [
      [
        ["amount", 0],
        ["description" "something"],
        ...
      ],
      ...
    ];
    

    Then you can use a custom sort function when you call obj.sort(customFunc).

    Reply

Leave a Comment