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

{/* Generated by src/codegen/lint-rule-docs.ts. Do not edit this section. */}

## Configure

Off by default. To turn it on:

```toml bunfig.toml
[lint.rules]
"sort-keys" = "error" # or "warn"
```

Every option, set to its default:

```toml bunfig.toml
[lint.rules]
"sort-keys" = [
  "error",
  "asc", # "asc" or "desc"
  {
    caseSensitive = true,
    natural = false,
    minKeys = 2,
    allowLineSeparatedGroups = false,
    ignoreComputedKeys = false,
  },
]
```

{/* End of the generated section. */}

## Examples

Reported:

{/* bad */}
```js
const user = {
  name: "Ada",
  email: "ada@example.com",
  role: "admin",
};
```

Not reported:

{/* good */}
```js
const user = {
  email: "ada@example.com",
  name: "Ada",
  role: "admin",
};

const settings = {
  theme: "dark",
  ...defaults,
  language: "en",
};

const { name, email } = user;
```

## Options

```toml 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:

{/* bad */}
```js
const prices = { item2: 5, item10: 9 };
```

With `natural` it isn't:

{/* good {"options": ["asc", {"natural": true}]} */}
```js
const prices = { item2: 5, item10: 9 };
```

Not reported with `allowLineSeparatedGroups`:

{/* good {"options": ["asc", {"allowLineSeparatedGroups": true}]} */}
```js
const user = {
  id: 1,
  name: "Ada",

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

Not reported with `ignoreComputedKeys`:

{/* good {"options": ["asc", {"ignoreComputedKeys": true}]} */}
```js
const labels = { name: "Name", [extraKey]: "Extra", email: "Email" };
```
