Move History

Fork Selected
  • Code
    export function transform(source: any) {
        const target = {};
        Object.entries(source).forEach(function ([k, v]) {
            k.split("_").slice(0, -1).reduce(function (node: {[key: string]: any}, element: string) {
                return node[element] ??= {};
            }, target)[k.slice(k.lastIndexOf("_") + 1)] = v;
        });
        return target;
    }
    Test Cases
    // See https://www.chaijs.com for how to use Chai.
    import { assert } from "chai";
    
    import { transform } from "./solution";
    
    // TODO Add your tests here
    describe("example", function() {
      const before = { a_b_c : 'value' }
        const before_2 = { a_b_c : 'value', d:'value_d' }
    const after = { 
    a : { 
      b: { 
        c: 'value'
        }
      }
    }
    const after_2 = { 
    a : { 
      b: { 
        c: 'value'
        }
      },
    d:'value_d'
    }
      it("test", function() {
        assert.deepEqual(transform(before), after);
         assert.deepEqual(transform(before_2), after_2);
      });
    });
    
  • Code
    • export function transform(obj: any) {
    • const _RegEx = new RegExp(/_/);
    • const underscoredProp = Object.keys(obj).find(key =>
    • _RegEx.test(key)) || '';
    • const value = obj[underscoredProp];
    • const propertList = underscoredProp.split('_').reverse();
    • let toAdd = {};
    • propertList.map((prop,index) => {
    • toAdd = index==0 ?{[prop]:value} : {[prop]:toAdd}
    • })
    • return toAdd;
    • export function transform(source: any) {
    • const target = {};
    • Object.entries(source).forEach(function ([k, v]) {
    • k.split("_").slice(0, -1).reduce(function (node: {[key: string]: any}, element: string) {
    • return node[element] ??= {};
    • }, target)[k.slice(k.lastIndexOf("_") + 1)] = v;
    • });
    • return target;
    • }