Ad
Objects
Data Types
Strings

Write a function that processes the properties of a given object, by the following rules:

  • Each property that has an underscore (_) in its name will be converted to a nested object
  • Properties that have only underscores or no properties, will remain the same
  • The last nested property will hold the original value

Example:

const beforeTransformation = {
  a_b_c: "value"
}

const afterTransformation = {
  a: {
    b: {
      c: "value"
    }
  }
}
Code
Diff
  • export const transform = (source: Record<string, any>): Record<string, any> => {
        const target = Object.create(null);
        // TODO: handle invalid property
        Object.entries(source).forEach(([key, value]) => {
            key.split("_").slice(0, -1).reduce((node: Record<string, any>, element: string) => {
                return node[element] ??= {};
            }, target)[key.slice(key.lastIndexOf("_") + 1)] = value;
        });
        return target;
    }
    • 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) {
    • export const transform = (source: Record<string, any>): Record<string, any> => {
    • const target = Object.create(null);
    • // TODO: handle invalid property
    • Object.entries(source).forEach(([key, value]) => {
    • key.split("_").slice(0, -1).reduce((node: Record<string, any>, element: string) => {
    • return node[element] ??= {};
    • }, target)[k.slice(k.lastIndexOf("_") + 1)] = v;
    • }, target)[key.slice(key.lastIndexOf("_") + 1)] = value;
    • });
    • return target;
    • }

Holy JS :)

Code
Diff
  • let larger_than_5=a=>a>5
    • def larger_than_5(a):
    • return a >5
    • let larger_than_5=a=>a>5