简体   繁体   中英

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 eg

[{ 
 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM