Sunday, 12 March 2017

Merge JS sub-objects into a JS object with joined keys

I'm writing template software for publishing node.js modules to GitHub and NPM. A small snippet of an example template:

Purpose

I have an object built up with all these properties, ex.

{
  "module" : {
    "name" : "test",
    "description" : "Test module"
...

The problem is that I need to merge this object's sub-objects so the final output looks something like this (for replacing the placeholders in the templates):

{
  "module.name" : "test",
  "module.description" : "Test module"
...

So I created my own function to do that:

/**
    Takes an object like
    {
        "type" : "meal",
        "pizza" : {
            "toppings" : ["pepperoni", "cheese"],
            "radius" : 6,
            "metadata" : {
                "id" : 24553
            }
        }
    }
    and changes it to
    {
        "type" : "meal",
        "pizza.toppings" : ["pepperoni", "cheese"],
        "pizza.radius" : 6,
        "pizza.metadata.id" : 244553
    }
*/
const mergeObjectsToKeys = object => {

    // Create an empty object to add properties to and then return

    const obj = { };

    // Loop through the passed in object's properties

    Object.entries(object).forEach(([key, value]) => {

        // Check if it is a sub-object or not

        if (typeof value === "object") {

            // If it is a sub-object, merge its properties with recursion and then put those keys into the master object

            const subObject = mergeObjectsToKeys(value);

            Object.entries(subObject).forEach(([key2, value2]) => {
                obj[key + "." + key2] = value2;
            });
        } else {

            // Otherwise, just put the key into the object to return

            obj[key] = value;
        }
    });
}

Two questions

  • Is this the correct way to write the software?
  • If so, is there a built-in function to merge the sub-objects, like shown above?


via Bennett

No comments:

Post a Comment