Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

sort-object-keys2

bluelovers9.1kMIT3.0.7TypeScript support: included

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

arr, array, deep, deterministic, function, js, key, keys, obj, object, order, re, re-order, recursive, recursively, sort, source, stable, util, utils, create-by-yarn-tool, create-by-tsdx

readme

sort-object-keys2

Returns a copy of an object with all keys sorted.

npm install sort-object-keys2

declare function sortObject<T>(object: T, options?: sortObject.IOptions & {
    useSource: true;
}): T;
declare function sortObject<T>(object: T, options?: sortObject.IOptions & {
    keys: string[];
    onlyKeys: true;
}): Partial<T>;
declare function sortObject<T>(object: T, options?: sortObject.IOptions): Partial<T>;
declare function sortObject<T>(object: T, sortFn: (a, b) => any): Partial<T>;
declare function sortObject<T>(object: T, sortWith: string[]): Partial<T>;

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()).

const assert = require('assert');
const sortObject = require('sort-object-keys2');

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

changelog

Change Log

All notable changes to this project will be documented in this file. See Conventional Commits for commit guidelines.

3.0.7 (2024-03-09)

♻️ Chores

3.0.6 (2024-03-09)

♻️ Chores

3.0.5 (2022-10-25)

♻️ Chores

3.0.4 (2022-10-14)

✨ Features

🛠 Build System

♻️ Chores

3.0.3 (2022-10-10)

✨ Features

  • allow input readonly keys array (01455f9)

♻️ Chores

3.0.2 (2022-09-26)

♻️ Chores

🔖 Miscellaneous

3.0.1 (2022-09-26)

📦 Code Refactoring

🛠 Build System