sort-object-keys
Sort an object's keys, including an optional key list
Last updated 3 months ago by GitHub Actions .
MIT · Repository · Bugs · Original npm · Tarball · package.json
$ cnpm install sort-object-keys 
SYNC missed versions from official npm registry.

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,
  }),
)

Current Tags

  • 2.1.0                                ...           latest (3 months ago)

8 Versions

  • 2.1.0                                ...           3 months ago
  • 2.0.1                                ...           5 months ago
  • 2.0.0                                ...           7 months ago
  • 1.1.3                                ...           6 years ago
  • 1.1.2                                ...           10 years ago
  • 1.1.1                                ...           10 years ago
  • 1.1.0                                ...           10 years ago
  • 1.0.0                                ...           10 years ago
Maintainers (1)
Downloads
Today 0
This Week 1
This Month 1
Last Day 0
Last Week 0
Last Month 0
Dependencies (0)
None
Dev Dependencies (3)
Dependents (1)

Copyright 2013 - present © cnpmjs.org | Home |