Code snippets for your daily life

Find useful snippets, bookmark and share them with other developers.

Latest Snippets

  • function flattenObject(objectTree) {
      const flatObject = {};
    
      if (!objectTree) {
        return flatObject;
      }
    
      Object.keys(objectTree).forEach((rootKey) => {
        if (Object.prototype.hasOwnProperty.call(objectTree, rootKey)) {
          // flatten deep nested objects
          if (typeof objectTree[rootKey] === 'object') {
            const deepObject = flattenObject(objectTree[rootKey]);
            Object.keys(deepObject).forEach((deepKey) => {
              if (Object.prototype.hasOwnProperty.call(deepObject, deepKey)) {
                flatObject[`${rootKey}.${deepKey}`] = deepObject[deepKey];
              }
            });
          } else {
            flatObject[rootKey] = objectTree[rootKey];
          }
        }
      });
    
      return flatObject;
    }
    
    const person = {
      Name: 'Goku',
      Attack: {
        Special: {
          Name: 'Kame Hame Ha',
          Power: '4000'
        },
        Final: {
          Name: 'Genkidama',
          Power: '> 9000'
        },
      }
    }
    
    /* 
      returns:
      {
        Name: 'Goku',
        'Attacks.Special.Name': 'Kame Hame Ha',
        'Attacks.Special.Power': '4000',
        'Attacks.Final.Name': 'Genkidama',
        'Attacks.Final.Power': '> 9000'
      }
    */
    flattenObject(person)
    Copy

    July 27th, 2020

    # Flatten an object of any depth

    Add to bookmarks

    A function which executes itself (so called recursion) is a good way to flatten an object of any depth.

    This algorithm uses two forEach() loops: One for the root layer of the current object and one for it's properties.

    At first, the outer loop will copy the property and it's values into flatObject. If the value is an object itself, the second loop will start.

    The inner loop copies the nested object into the flatObject. The keys of the nested objects will be merged to a dot-notation key like key1.key2.

  • <!DOCTYPE html>
    <html>
      <body>
        <input id="awesomeInput" value="2" />
        
        <script>
          window.$ = document.querySelector.bind(document);
          window.$$ = document.querySelectorAll.bind(document);
          
          setTimeout(() => {
            let awesomeInput = $('#awesomeInput');
            awesomeInput.value = 10;
          }, 5000);
        </script>
      </body>
    </html>
    Copy

    July 26th, 2020

    # Select elements the jQuery-way without jQuery

    Add to bookmarks

    We created a new $and $$ function on the window object via bind(). This way our newly created functions will be the shortcuts for the querySelector and querySelectorAll method.

    The example updates the value of the input from 2 to 10 after 5000 ms by using our jQuery-like selector.

  • let sayan = {
      name: 'Son Goku',
      power: 9001
    }
    
    let character = Object.freeze(sayan);
    character.name = 'Vegeta';
    
    // output: { name: 'Son Goku', power: 9001 }
    console.log(character)
    Copy

    April 12th, 2020

    # Object.freeze() - How to prevent changes to an object?

    Add to bookmarks

    Object.freeze() can prevent changes to an object. If you're in strict mode (use strict; in the first line of your code), your browser will throw an error.

  • const numbers = [1, 2, [3, 4], [5, 6]]
    
    // returns [1, 2, 3, 4, 5, 6]
    numbers.flat()
    Copy

    April 12th, 2020

    # flat() - Flatten an array

    Add to bookmarks

    flat() can be used to flatten arrays with the depth of one (e.g. [1, [2, 3], 4]). It returns a new array.

  • const numbers = [1, -1, 2, 42]
    const reducer = (accumulator, currentValue) => accumulator + currentValue
    
    // returns 44
    numbers.reduce(reducer)
    
    // initial value is 2, returns 46
    numbers.reduce(reducer, 2)
    Copy

    April 12th, 2020

    # reduce() - Reduce an array to one value

    Add to bookmarks

    reduce() can be used to reduce an array of multiple elements to just one value. This can be coming handy for instance when calculating the sum of all elements of an array.

    This is achieved by applying a reducer function as first parameter and an optional initial value as second parameter: reduce(reducer()[, initialValue]).

    reduce() returns one value and doesn't mutate the original array.

HomeBookmarks