What is the best way to generate a nested object arrangement using a path (series of keys)?

I have a challenge of creating nested objects from arrays of strings to store the sequence of input strings. Originally, I was only generating chains with a depth of 2, but now I need to expand this capability to create higher-depth chains.

Essentially, I am looking to transform an array like this:

["test1", "test2", "test3", "test4"]

into the following format:

{
    "test1":
    {
        "test2":
        {
            "test3":
            {
                "test4": {}
            }
        }
    }
}

Answer №1

If you're looking to create an object from a given path, then you might want to consider using Array#reduce:

function generateObjectFromPath (path) {
  var result = {}
  
  path.reduce(function (obj, key) {
    return (obj[key] = {})
  }, result)
  
  return result
}

var samplePath = ["example1", "example2", "example3", "example4"]

console.log(generateObjectFromPath(samplePath))
.as-console-wrapper { min-height: 100%; }

Answer №2

I had a problem similar to this that I wanted to tackle by setting a value at the end of the path in the resulting object. To achieve this, I took inspiration from gyre's original function and added some extra tweaks to cater to my specific needs.

// Transform an array representing a key path into a nested object
//
// Optional arguments:
//     - value to set at the end of the path
//     - initial object
// 
// Example: let house = createObjectFromPath(['kitchen', 'fridge'], 'empty', {civic: 123})
//     => house = {civic: 123, kitchen: {fridge: 'empty'}}
const createObjectFromPath = (path, value = {}, obj = {}) =>
{
    path.reduce((result, key, i, source) =>
        {
            if(i === (source.length - 1))
            {
                return (result[key] = value)
            }
            else
            {
                return (result[key] = {})
            }
        },
        obj
    )
    
    return obj;
}


// Demonstration: house = {civic: 123, kitchen: {fridge: 'empty'}}
console.log(
  createObjectFromPath(
    ['kitchen', 'fridge'],
    'empty',
    {civic: 123}
  )
)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

After refreshing the page, the console log within the React useEffect function ceases to function

Incorporating the 'useEffect' function to fetch data and store it in the 'ratings' array has proven successful. However, there seems to be an issue when attempting to iterate through the elements of the 'ratings' array for log ...

What is causing this form to submit?

I need help with sending emails via AJAX. My problem is that the form keeps submitting and refreshing, even though I haven't used GET to send anything in the URL. HTML: <form onsubmit="ajaxEmail(); return false;" > <input type=" ...

How can an Angular Component be created in the browser using the standard method?

Attempting to develop a basic Angular example using JS/ESM. It has been some time since working within the angular environment, and there appear to be two primary choices: Utilizing the UMD lib (preferably to be avoided) Using the ESM2015 folder and loadi ...

Unable to display response following the submission of a POST request

I'm encountering an issue when attempting to display the response of a post request using node and request. While I can see the response in the console within the service, it does not make its way to the controller. Any insights on why this may be hap ...

How can I implement custom code to run in all Ajax requests in Ext JS without having to manually insert it into each individual request?

When a user is logged in, ajax requests function properly. However, if the session becomes invalidated, the ajax returns a login screen and displays it as ajax content. I am wondering if it is feasible to incorporate custom code in Ext JS that would be e ...

Updating the state using ui-router

The application consists of pages labeled as X, Y, and Z. The intended route is to navigate from page X to select details, then move onto page Y to select additional details, and finally land on page Z. I wish that upon clicking the window's back butt ...

WordPress header causing issues with Document.write()

I have a JavaScript function that utilizes AJAX to retrieve data from a PHP file. Previously, I utilized document.write(data) to display the retrieved content and it worked smoothly on its own. However, upon incorporating the script into WordPress via hea ...

Is it possible to invoke a JavaScript function within PHP code?

When setting up server side validations on my login form, I want to display error messages directly below the validated control when an error occurs. However, I am currently having trouble calling a JavaScript function from my PHP code to handle this. < ...

Add items to a new array with a property set to true, if they are present in the original array

Could someone assist me with the following situation? I need an array of strings. A function is required to map the array of strings, assigning each element a name and key, while also adding another object "checked: false". Another function should take t ...

Is it possible to use AngularJS promises without callbacks?

Typically, when I want to retrieve data asynchronously, I would use the following approach: var promise = $http.get('/api/v1/movies/avengers'); promise.then( function(payload) { $scope.movieContent = payload; }); This scenario is quite ...

Add the URL link according to the specific domain name

I am looking for a way to attach additional URL parameters to any links that contain example.com on a webpage. The current script I have only works if the link does not already have parameters attached to it. <script> document.body.innerHTML = d ...

What is the best way to implement a constant countdown timer in JQuery that remains unaffected by page refreshes?

I have implemented a time countdown feature in my web app using this jQuery plugin. However, I am facing an issue where the countdown starts from the beginning every time the page is refreshed. I want the countdown to remain consistent for a month (30 days ...

Enhancing the functionality of an existing framework through the integration of a

My coding style involves a lot of ASP.NET MVC and jQuery, particularly with ajax calls that return json. Lately, I've been tinkering with organizing my code structure by creating an object within the global object which contains success and fail callb ...

Having trouble with Discord.js version 12 and the messageReactionAdd event not triggering properly?

client.on('messageReactionAdd', (reaction, user) => { console.log('If you see this I actually work...'); }); I am having some trouble with my code. Despite setting up a simple console log, it seems like the code is not running prope ...

Error: [BITFIELD_INVALID_RANGE]: The bitfield flag or number entered is not valid: 3214336

Currently working on a Discord Dashboard project, but encountering an unusual error: Invalid bitfield flag or number 3214336. This issue arises when attempting to retrieve the guilds that a user has MANAGE_GUILDS permission for. Below is the snippet of my ...

Creating visual content on a website

I'm currently working on a project where I need to showcase the results of a numerical model I am operating. My goal is to gather user input in the form of latitude/longitude coordinates, utilize php (or a similar tool) to trigger a python script that ...

What method can I use to identify the most widely-used edition of a specific npm module?

While the npm registry does provide metrics on the most depended packages, have you ever wondered if it's possible to determine the most popular version of a specific package? For example, as a user considering upgrading to react-router^4.0.0, wouldn ...

What is the best way to retrieve the state value in react once it has been changed?

How can I ensure that the react state 'country' is immediately accessible after setting it in the code below? Currently, I am only able to access the previous state value in the 'country' variable. Is there a method such as a callback o ...

The Strapi admin panel seems to be stuck on an eternal loading loop when accessed locally on my localhost

section, some unexpected issues arose recently. This sudden occurrence took place following some modifications that involved adding a significant number of new Fields attributes to a specific Collection Type. As a result, my Strapi CMS NodeJS backend is n ...

Unleash the power of arrays within arrays in PySpark to enhance your column explosion

I am looking to break down the data in a specific column: [[[-77.1082606, 38.935738]] ,Point] My desired output format is: column 1 column 2 column 3 -77.1082606 38.935738 Point Is there a way to achieve this using PyS ...