Share your code. npm Orgs help your team discover, share, and reuse code. Create a free org »

    recursive-json-key-transformpublic

    recursive-json-key-transform

    Apply a string transformation recursively to all keys in a JSON-compatible object.

    It's easiest to just show how this works.

    Installation (get it from npm)

    npm install recursive-json-key-transform
    

    Usage

    /**
     * ES6/ES2015 syntax
     */
    import recursiveJSONKeyTransform from 'recursive-json-key-transform';
    
    const convertAllKeysFromPascalCaseToCamelCase = (
      recursiveJSONKeyTransform((str) => {
        return str[0].toLowerCase() + str.slice(1);
      })
    );
    
    const data = { Data1: { FieldA: 1, FieldB: false },
                   Data2: [ { FieldC: "hello" } ] };
    
    const camelCaseData = convertAllKeysFromPascalCaseToCamelCase(data);
    
    console.log(camelCaseData);
    /**
     * prints:
     * { data1: { fieldA: 1, fieldB: false },
     *   data2: [ { fieldC: 'hello' } ] }
     *
     */
    

    recursiveJSONKeyTransform accepts one argument, a transformer function that accepts a string and returns a string. The result of recursiveJSONKeyTransform(transformerFn) is another function, which accepts a JSON-compatible JavaScript object. It returns a deep copy of that object with all object keys transformed according to the specified transformer function (including objects nested inside of arrays).

    Any object will work, but if it contains JSON-incompatible properties (e.g. functions), they will be ignored (or interpreted as empty objects). The module's intended use is for JSON responses from APIs, which may contain object keys in a format different than your application's convention.

    install

    npm i recursive-json-key-transform

    Downloadsweekly downloads

    114

    version

    0.2.0

    license

    MIT

    repository

    githubgithub

    last publish

    collaborators

    • avatar