GithubHelp home page GithubHelp logo

bevry / sortobject Goto Github PK

View Code? Open in Web Editor NEW
6.0 2.0 3.0 746 KB

Deeply sort an object by its keys without mangling any arrays inside of it

License: Other

JavaScript 21.79% TypeScript 78.21%
client-side nodejs object-sort data-manipulation

sortobject's Introduction

Sort Object

Status of the GitHub Workflow: bevry NPM version NPM downloads
GitHub Sponsors donate button ThanksDev donate button Patreon donate button Liberapay donate button Buy Me A Coffee donate button Open Collective donate button crypto donate button PayPal donate button
Discord server badge Twitch community badge

Returns a copy of an object, sorted deeply by its keys, without mangling any arrays inside of it

Usage

Complete API Documentation.

import sortObject from 'sortobject'
const fixture = {
    c: true,
    a: true,
    b: null,
    d: [
        {
            c: true,
            a: true,
            b: null,
        },
        {
            c: true,
            a: true,
            b: null,
            d: [
                {
                    c: true,
                    a: true,
                    b: null,
                },
            ],
        },
    ],
}
const actual = sortObject(fixture)
console.log(JSON.stringify(actual, null, 4)) /* {
    "a": true,
    "b": null,
    "c": true,
    "d": [
        {
            "a": true,
            "b": null,
            "c": true
        },
        {
            "a": true,
            "b": null,
            "c": true,
            "d": [
                {
                    "a": true,
                    "b": null,
                    "c": true
                }
            ]
        }
    ]
} */

Install

  • Install: npm install --save sortobject
  • Import: import pkg from ('sortobject')
  • Require: const pkg = require('sortobject').default
import pkg from 'https://unpkg.com/sortobject@^5.6.0/edition-deno/index.ts'
<script type="module">
    import pkg from '//cdn.skypack.dev/sortobject@^5.6.0'
</script>
<script type="module">
    import pkg from '//unpkg.com/sortobject@^5.6.0'
</script>
<script type="module">
    import pkg from '//dev.jspm.io/[email protected]'
</script>

This package is published with the following editions:

  • sortobject/source/index.ts is TypeScript source code with Import for modules
  • sortobject/edition-browsers/index.js is TypeScript compiled against ES2022 for web browsers with Import for modules
  • sortobject aliases sortobject/edition-es2022/index.js
  • sortobject/edition-es2022/index.js is TypeScript compiled against ES2022 for Node.js 4 || 6 || 8 || 10 || 12 || 14 || 16 || 18 || 20 || 21 with Require for modules
  • sortobject/edition-es2022-esm/index.js is TypeScript compiled against ES2022 for Node.js 12 || 14 || 16 || 18 || 20 || 21 with Import for modules
  • sortobject/edition-types/index.d.ts is TypeScript compiled Types with Import for modules
  • sortobject/edition-deno/index.ts is TypeScript source code made to be compatible with Deno

History

Discover the release history by heading on over to the HISTORY.md file.

Backers

Code

Discover how to contribute via the CONTRIBUTING.md file.

Authors

Maintainers

Contributors

Finances

GitHub Sponsors donate button ThanksDev donate button Patreon donate button Liberapay donate button Buy Me A Coffee donate button Open Collective donate button crypto donate button PayPal donate button

Funders

Sponsors

  • Andrew Nesbitt — Software engineer and researcher
  • Balsa — We're Balsa, and we're building tools for builders.
  • Codecov — Empower developers with tools to improve code quality and testing.
  • Poonacha Medappa
  • Rob Morris
  • Sentry — Real-time crash reporting for your web apps, mobile apps, and games.
  • Syntax — Syntax Podcast

Donors

License

Unless stated otherwise all works are:

and licensed under:

sortobject's People

Contributors

balupton avatar dependabot-preview[bot] avatar dependabot[bot] avatar github-actions[bot] avatar jameslnewell avatar sinewyk avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

sortobject's Issues

Problem with 1.1.0 release (with webpack)

There seems to be a problem with the latest release, using webpack

Works fine when using version 1.0.0

First error is

WARNING in ../~/sortobject/index.js
Critical dependencies:
3:63-70 require function is used in a way in which dependencies cannot be statically extracted
 @ ../~/sortobject/index.js 3:63-70

Next we get loads of something like this

WARNING in ../~/sortobject/package.json
Module parse failed: /path/to/project/node_modules/sortobject/package.json Unexpected token (2:9)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (2:9)
    at Parser.pp.raise (/path/to/project/node_modules/acorn/dist/acorn.js:920:13)
    at Parser.pp.unexpected (/path/to/project/node_modules/acorn/dist/acorn.js:1483:8)
    at Parser.pp.semicolon (/path/to/project/node_modules/acorn/dist/acorn.js:1462:73)
    at Parser.pp.parseExpressionStatement (/path/to/project/node_modules/acorn/dist/acorn.js:1976:8)
    at Parser.pp.parseStatement (/path/to/project/node_modules/acorn/dist/acorn.js:1754:188)
    at Parser.pp.parseBlock (/path/to/project/node_modules/acorn/dist/acorn.js:1991:21)
    at Parser.pp.parseStatement (/path/to/project/node_modules/acorn/dist/acorn.js:1735:19)
    at Parser.pp.parseTopLevel (/path/to/project/node_modules/acorn/dist/acorn.js:1648:21)
    at Parser.parse (/path/to/project/node_modules/acorn/dist/acorn.js:1616:17)
    at Object.parse (/path/to/project/node_modules/acorn/dist/acorn.js:882:44)
    at Parser.parse (/path/to/project/node_modules/webpack/lib/Parser.js:902:15)
    at DependenciesBlock.<anonymous> (/path/to/project/node_modules/webpack/lib/NormalModule.js:104:16)
    at DependenciesBlock.onModuleBuild (/path/to/project/node_modules/webpack-core/lib/NormalModuleMixin.js:310:10)
    at nextLoader (/path/to/project/node_modules/webpack-core/lib/NormalModuleMixin.js:275:25)
    at /path/to/project/node_modules/webpack-core/lib/NormalModuleMixin.js:259:5
    at Storage.provide (/path/to/project/node_modules/enhanced-resolve/lib/CachedInputFileSystem.js:52:20)
    at CachedInputFileSystem.readFile (/path/to/project/node_modules/enhanced-resolve/lib/CachedInputFileSystem.js:140:24)
    at DependenciesBlock.onLoadPitchDone (/path/to/project/node_modules/webpack-core/lib/NormalModuleMixin.js:255:7)
    at DependenciesBlock.loadPitch (/path/to/project/node_modules/webpack-core/lib/NormalModuleMixin.js:182:27)
    at DependenciesBlock.doBuild (/path/to/project/node_modules/webpack-core/lib/NormalModuleMixin.js:241:4)
    at DependenciesBlock.build (/path/to/project/node_modules/webpack/lib/NormalModule.js:84:14)
    at Compilation.buildModule (/path/to/project/node_modules/webpack/lib/Compilation.js:126:9)
 @ ../~/sortobject ^\.\/.*$

 WARNING in ../~/sortobject/HISTORY.md
Module parse failed: /path/to/project/node_modules/sortobject/HISTORY.md Unexpected character '#' (1:0)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected character '#' (1:0)
    at Parser.pp.raise (/path/to/project/node_modules/acorn/dist/acorn.js:920:13)
    at Parser.pp.getTokenFromCode (/path/to/project/node_modules/acorn/dist/acorn.js:2813:8)
    at Parser.pp.readToken (/path/to/project/node_modules/acorn/dist/acorn.js:2508:15)
    at Parser.pp.nextToken (/path/to/project/node_modules/acorn/dist/acorn.js:2500:71)
    at Parser.parse (/path/to/project/node_modules/acorn/dist/acorn.js:1615:10)
    at Object.parse (/path/to/project/node_modules/acorn/dist/acorn.js:882:44)
    at Parser.parse (/path/to/project/node_modules/webpack/lib/Parser.js:902:15)
    at DependenciesBlock.<anonymous> (/path/to/project/node_modules/webpack/lib/NormalModule.js:104:16)
    at DependenciesBlock.onModuleBuild (/path/to/project/node_modules/webpack-core/lib/NormalModuleMixin.js:310:10)
    at nextLoader (/path/to/project/node_modules/webpack-core/lib/NormalModuleMixin.js:275:25)
    at /path/to/project/node_modules/webpack-core/lib/NormalModuleMixin.js:259:5
    at Storage.finished (/path/to/project/node_modules/enhanced-resolve/lib/CachedInputFileSystem.js:38:16)
    at /path/to/project/node_modules/graceful-fs/graceful-fs.js:78:16
    at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:404:3)
 @ ../~/sortobject ^\.\/.*$

Your .dependabot/config.yml contained invalid details

Dependabot encountered the following error when parsing your .dependabot/config.yml:

The property '#/update_configs/0/automerged_updates/0/match/update_type' value "security" did not match one of the following values: all, security:patch, semver:patch, semver:minor, in_range

Please update the config file to conform with Dependabot's specification using our docs and online validator.

Iterations + Contribution

Since the object/array .length doesn't change, why is the need to calculate the .length on each iteration cycle ? I've also improved the code, following the D.R.Y and readability philosopy.

Old code:

module.exports = function sortObject (obj, comparator) {
    // Arrays
    if ( Array.isArray(obj) ) {
        const result = []
        for ( let i = 0; i < obj.length; ++i ) {
            // Fetch
            let value = obj[i]

            // Recurse if object or array
            if ( value != null && typeof value === 'object' ) {
                value = sortObject(value, comparator)
            }

            // Push
            result.push(value)
        }
        return result
    }

    // Objects
    else {
        const result = {}
        const sortedKeys = Object.keys(obj).sort(comparator)
        for ( let i = 0; i < sortedKeys.length; ++i ) {
            // Fetch
            const key = sortedKeys[i]
            let value = obj[key]

            // Recurse if object or array
            if ( value != null && typeof value === 'object' ) {
                value = sortObject(value, comparator)
            }

            // Push
            result[key] = value
        }
        return result
    }
}

New one:

var iterArray = function(arr, obj, toKeyVal, comparator) {
    var result = toKeyVal ? {} : [],
        value = null;

    arr.forEach(function(elem) {
        value = toKeyVal ? obj[elem] : elem;
        if (value !== null && typeof value === 'object') {
            value = sortObject(value, comparator);
        }
        if (toKeyVal) {
            result[elem] = value;
        } else {
            result.push(value);
        }
    });
    return toKeyVal ? result : result.sort();
};

var sortObject = function (obj, comparator) {
    // Arrays
    if ( Array.isArray(obj) ) {
        return iterArray(obj, obj, false, comparator);
    }

    // Objects
    else {
        return iterArray(Object.keys(obj).sort(),
                obj, true, comparator);
    }
};

15 hours later: replaced return result; to return toKeyVal ? result : result.sort();, so the array elements to be sorterd alphabetically in case of

d: ['b','d','e','a','c']

TypeScript typings

The provided solution in the readme.md to get the typings to work for TypeScript is not an option for many projects (including ours). I've made a PR to DefinitelyTyped to add TS typings of sortobject, but they suggested to open an issue in here.

Are you willing to add TypeScript typings to sortobject to help TypeScript users if I do make a PR to this repo (also meaning that these types do need to be updated together with future changes)? Otherwise, are you fine with it if DefinitelyTyped will merge mine PR so that users get the typings from there?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.