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

```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,
  },
]
```

## Examples

Reported:

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

Not reported:

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

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

With `natural` it isn't:

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

Not reported with `allowLineSeparatedGroups`:

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

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

Not reported with `ignoreComputedKeys`:

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