Skip to content
NewBun 1.4.5 is out. Release notes
AphrodyBun

Linter · Rules

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

Reported:

const user = {
  name: "Ada",
  email: "ada@example.com",
  role: "admin",
};

Not reported:

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:

OptionDefaultWhat it does
caseSensitivetrueCapital letters sort before lowercase letters. With false, case is ignored.
naturalfalseCompare numbers in keys by value, so item2 comes before item10.
minKeys2Only check objects with at least this many properties.
allowLineSeparatedGroupsfalseA blank line between properties starts a new group that's sorted separately.
ignoreComputedKeysfalseSkip 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:

const prices = { item2: 5, item10: 9 };

With natural it isn't:

const prices = { item2: 5, item10: 9 };

Not reported with allowLineSeparatedGroups:

const user = {
  id: 1,
  name: "Ada",

  city: "London",
  country: "UK",
};

Not reported with ignoreComputedKeys:

const labels = { name: "Name", [extraKey]: "Extra", email: "Email" };