sort-keys
Require the keys of object literals to be sorted
In a long object literal, sorted keys are quick to find, and two people who add a key put it in the same place.
Each key is compared with the one before it. A spread such as ...defaults starts the comparison over, because moving a key across a spread can change the result. Destructuring patterns aren't checked.
Configure#
Off by default. To turn it on:
bunfig.toml
[lint.rules]
"sort-keys" = "error" # or "warn"Every option, set to its default:
bunfig.toml
[lint.rules]
"sort-keys" = [
"error",
"asc", # "asc" or "desc"
{
caseSensitive = true,
natural = false,
minKeys = 2,
allowLineSeparatedGroups = false,
ignoreComputedKeys = false,
},
]Examples#
example.js1 problem
const user = {
name: "Ada",
emailExpected object keys to be in ascending order. email should be before name.: "ada@example.com",
role: "admin",
};example.jsNo problems
const user = {
email: "ada@example.com",
name: "Ada",
role: "admin",
};
const settings = {
theme: "dark",
...defaults,
language: "en",
};
const { name, email } = user;Options#
bunfig.toml
[lint.rules]
sort-keys = ["error", "asc", { natural = true, minKeys = 5 }]The first option is the direction: "asc" (default) or "desc". The second is an object:
| Option | Default | What it does |
|---|---|---|
caseSensitive | true | Capital letters sort before lowercase letters. With false, case is ignored. |
natural | false | Compare numbers in keys by value, so item2 comes before item10. |
minKeys | 2 | Only check objects with at least this many properties. |
allowLineSeparatedGroups | false | A blank line between properties starts a new group that's sorted separately. |
ignoreComputedKeys | false | Skip computed keys such as [id]. A computed key then starts the comparison over, like a spread. |
By default item10 sorts before item2, character by character, so this is reported:
example.js1 problem
const prices = { item2: 5, item10Expected object keys to be in ascending order. item10 should be before item2.: 9 };With natural it isn't:
example.jswith
"asc", { "natural": true }No problemsconst prices = { item2: 5, item10: 9 };Not reported with allowLineSeparatedGroups:
example.jswith
"asc", { "allowLineSeparatedGroups": true }No problemsconst user = {
id: 1,
name: "Ada",
city: "London",
country: "UK",
};Not reported with ignoreComputedKeys:
example.jswith
"asc", { "ignoreComputedKeys": true }No problemsconst labels = { name: "Name", [extraKey]: "Extra", email: "Email" };