sort-object-keys

Sort an object's keys, including an optional key list

MIT 8 个版本
安装
npm install sort-object-keys
yarn add sort-object-keys
pnpm add sort-object-keys
bun add sort-object-keys
README

Sort Object

Build Status

Returns a copy of an object with all keys sorted.

The second argument is optional and is used for ordering - to provide custom sorts. You can either pass an array containing ordered keys or a function to sort the keys (same signature as in Array.prototype.sort()).

import assert from 'assert'
import sortObject from 'sort-object-keys'

assert.equal(
  JSON.stringify({
    c: 1,
    b: 1,
    d: 1,
    a: 1,
  }),
  JSON.stringify({
    a: 1,
    b: 1,
    c: 1,
    d: 1,
  }),
)

assert.equal(
  JSON.stringify(
    sortObject(
      {
        c: 1,
        b: 1,
        d: 1,
        a: 1,
      },
      ['b', 'a', 'd', 'c'],
    ),
  ),
  JSON.stringify({
    b: 1,
    a: 1,
    d: 1,
    c: 1,
  }),
)

function removeKeyAncCompareIndex(keyA, keyB) {
  var a = parseInt(keyA.slice(4))
  var b = parseInt(keyB.slice(4))
  return a - b
}

assert.equal(
  JSON.stringify(
    sortObject(
      {
        'key-1': 1,
        'key-3': 1,
        'key-10': 1,
        'key-2': 1,
      },
      removeKeyAncCompareIndex,
    ),
  ),
  JSON.stringify({
    'key-1': 1,
    'key-2': 1,
    'key-3': 1,
    'key-10': 1,
  }),
)
版本列表
2.1.0 2026-01-12
2.0.1 2025-10-30
2.0.0 2025-09-16
1.1.3 2019-12-10
1.1.2 2015-12-14
1.1.1 2015-12-02
1.1.0 2015-12-02
1.0.0 2015-11-30