What is the best way to convert string dot notation into a nested object structure?

Is there a way to convert a dot notation string such as 'a.b.c.d' into an Object? And if the Object referenced doesn't exist, can we automatically create an empty one?

var str = 'a.b.c.d'
var obj = {}

// Now what?

function dotToObj(obj, str) {
    // Code implementation needed here 
    obj[?] = obj[?] || {}            
     }

// In case the object doesn't exist, let's create an empty object.

var result = dotToObj(obj, str);


console.log(result)

// Expected Output:
Object {a: Object}
    a: Object
        b: Object
            c: Object
                d: Object
                __proto__: Object
            __proto__: Object
        __proto__: Object
    __proto__: Object

Answer №1

To break down a string and utilize its components as references, you can employ the Array.prototype.reduce() method. In this code snippet, the variable obj serves as the initial object, with each part of the split string used to create nested objects within it.

var str = 'a.b.c.d',
    obj = {};

str.split('.').reduce(function (r, a) {
    r[a] = r[a] || {};
    return r[a];
}, obj);

document.write('<pre>' + JSON.stringify(obj, 0, 4) + '</pre>');

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

Create original identifiers for dynamically generated material

I have developed a custom invoice tool that has the capability to dynamically add rows. Here is the code snippet responsible for generating new rows: $("#addrow").click(function(){ $(".item-row:last").after('<tr class="item-row"><td> ...

The JQuery category filtering feature malfunctions when a category consists of more than two words

Utilizing Jquery, I have implemented a feature that displays project categories and allows users to filter projects based on the selected category. To view the code pen for this implementation, please click here: https://codepen.io/saintasia/pen/dzqZov H ...

Why does this switch case statement fail to effectively replace the elements of the text in order to unravel this JavaScript problem?

Question I need help converting special characters to HTML entities in a string: &, <, >, " (double quote), and ' (apostrophe). My Code function convertHTML(str) { let tempArr = ['a']; let newArr = []; let regex ...

Modifying the size of an element with D3 when hovering with the mouse

In a previous project, I created a stacked bar chart with some interesting mouseover effects. Now, I want to take it a step further by changing the size of the rectangle that the user hovers over, returning it to its original size once they move away. My ...

Create text that alternates between blinking and changing content simultaneously

I'm currently working on a website and I am curious about how to achieve the effect of making text blink and change content simultaneously, similar to what is seen on this particular website . Sorry for not being more specific in my question. Thank yo ...

Unsuccessful attempt at testing RequireJS in a straightforward manner

As a beginner in RequireJS, I am currently experimenting to gain some experience. My goal is to make require load basic Angular first and then manually bring in Angular UI Bootstrap. However, I am encountering an issue where UI Bootstrap complains that ang ...

Adding or removing a class using Jquery based on the condition of form validation

I am facing a problem with the following code that adds and removes classes to bring the next stage of the form. The form progresses step by step where certain fields need to be filled before validation on the next button, followed by filling other fields. ...

Checking the validity of subdomain names using JavaScript/jQuery

For users signing up, my form allows them to choose a subdomain for their account. The valid characters allowed in the subdomain are letters, numbers, and dashes. Spaces and most special characters should be filtered out. http://_________.ourapp.com To r ...

Transitioning from Event-driven Object Oriented design to Redux structure

I currently have a structure that is mostly object-oriented and I am considering migrating to React/Redux due to handling issues with events. I have various modules with objects structured like this: User { getName() getSurname() etc... } These obj ...

Table Header Stays Put Without Shrinking or Expanding with Window Adjustment

I have a sticky table header that stays at the top when scrolling down on my web page. To achieve this effect, I followed the solution provided on css-tricks.com/persistent-headers/. However, I encountered an issue where the sticky table header does not ...

Deleting data from Firebase in Angular can be easily done using the AngularFire library. By

I am attempting to remove specific values from my Firebase database. I need to delete this entry from Firebase: https://i.stack.imgur.com/CAUHX.png So far, I have tried using a button to trigger the delete function like this: <div class="single-bfunc ...

What are the steps for adding node packages to sublime text?

Is there a way to install node packages directly from Sublime Text instead of using the command line? If so, what is the process for doing this? I'm not referring to Package Control; I'm specifically interested in installing npm packages like th ...

Having trouble importing the module I developed in Node

I've been struggling to understand why this import is failing. Despite trying numerous approaches, modifying the export and import based on various tutorials online, it continues to result in failure every time. This should be a simple task in theory. ...

Using MVC4 and jQuery to unselect items from an Html.CheckboxListFor

In my search page, I am utilizing jQuery to toggle the visibility of different sections based on user input. Specifically, I have a Html.Textbox and Html.CheckboxListFor that are shown or hidden depending on whether there is any input in the textbox or if ...

The Ajax request is not passing the values of the submit button as expected

In my current setup, I am using ajax code to send name/email/message parameters to a "messageaction.cfm" template and then display those same 3 parameters on the original submission page. The code works fine in achieving this functionality: <script ...

Incorporate PNG files with pre-defined labels in a React element

In my application, there is a collection of PNG images with filenames consisting of only 2 letters like aa.png, ab.png, ac.png, and so on. Additionally, there is an API endpoint that retrieves an array of objects with a property "name" containing 3 letter ...

Issue with passing parameter values in MVC Html.ActionLink

Currently, I am experimenting with MVC for a demonstration and have managed to put together some components. However, I am encountering difficulties with an Html.ActionLink. The goal is to display a series of dropdown lists to the user that must be selecte ...

ReactJS Chatkit has not been initialized

I made some progress on a tutorial for creating an Instant Messenger application using React and Chatkit. The tutorial can be found in the link below: https://www.youtube.com/watch?v=6vcIW0CO07k However, I hit a roadblock around the 19-minute mark. In t ...

Potential issue of excessive memory usage in node.js when running an Express server with PM2

Currently, I am focusing on a specific aspect of a suite of services designed to work in conjunction with an app/platform. The particular area that requires assistance is related to a vanilla express server used to provide our client app (a react app). We ...

Decoding JSON using JavaScript

I am dealing with a webservice that uses RestEasy to return a JSON object with a List element. When I try to parse the results in a JavaScript loop, everything works fine if there are two or more elements in the List. However, if there is only one element, ...