What is the best way to dynamically access or create nested objects by iterating through a loop based on a given number?

Can someone assist me in refactoring a couple of if-statements that are almost identical, but differ only in hierarchy within the currentHierarchie object? I am looking to consolidate these into a loop or similar construct. The number of if statements should correspond to laneAndAllParentLanesIds.length.

private createLaneHierarchieStructure(laneAndAllParentLanesIds: any[], currentHierarchie) {
    for (let i = 0; i < laneAndAllParentLanesIds.length; i++) {
        const obj = currentHierarchie;
        const keys = laneAndAllParentLanesIds;

        if (i === 0 && !obj[keys[i]])
            obj[keys[i]] = {};

        if (i === 1 && !obj[keys[i - 1]][keys[i]])
            obj[keys[i - 1]][keys[i]] = {};

        if (i === 2 && !obj[keys[i - 2]][keys[i - 1]][keys[i]])
            obj[keys[i - 2]][keys[i - 1]][keys[i]] = {};

        if (i === 3 && !obj[keys[i - 3]][keys[i - 2]][keys[i - 1]][keys[i]])
            obj[keys[i - 3]][keys[i - 2]][keys[i - 1]][keys[i]] = {};

        if (i === 4 && !obj[keys[i - 4]][keys[i - 3]][keys[i - 2]][keys[i - 1]][keys[i]])
            obj[keys[i - 4]][keys[i - 3]][keys[i - 2]][keys[i - 1]][keys[i]] = {};
    }
    return currentHierarchie;
}

View an example response generated by this code (after invoking it multiple times and storing the results in the same object (currentHierarchie) using:

for (let i = 0; i < boards.length; i++) {
    let laneHierarchie = {};
    boards[i]['info']['lanes'].forEach(lane => {
        const laneAndAllParentLanesIds = this.getAllParentLanes(i, lane);
        laneHierarchie = this.createLaneHierarchieStructure(laneAndAllParentLanesIds, laneHierarchie);
    });
    console.log(laneHierarchie);
}

Answer №1

To optimize the code, you can move the declaration and initialization of the obj variable outside of the for loop. Then, use a single value as a key to check and assign an empty array if needed.

After that, set the last property to obj for the next iteration.

const obj = currentHierarchie;

for (let key of laneAndAllParentLanesIds) {
    obj[key] = obj[key] || {};
    obj = obj[key];
}

An alternative version using reduce:

void laneAndAllParentLanesIds.reduce((o, id) => o[id] = o[id] || {}, currentHierarchie);

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

What steps should be taken to effectively integrate Amplify Authenticator, Vue2, and Vite?

Embarked on a fresh Vue2 project with Vite as the build tool. My aim is to enforce user login through Cognito using Amplify. However, when I execute npm run dev, I encounter the following issue: VITE v3.1.3 ready in 405 ms ➜ Local: http://127.0.0 ...

Exploring the integration of functions from external JavaScript libraries into Angular factories and controllers

Is there a way to incorporate the functions from these libraries into my Angular factory? <head> <script type="text/javascript" src="js/3rdparty/strophe.js"></script> <script type="text/javascript" src="js/3rdparty/xml2json.js">< ...

Avian-themed masking feature for jCarousel

Currently, I have a series of images in constant motion using jCarousel. Only one image is visible fully at any given time, and I am looking to create a "feathering" effect on the edges of the carousel so that the images smoothly fade in and out as they co ...

Encountering a blank page and error message on Vue JS while attempting to generate a JSON file within the

Recently, I encountered a peculiar problem while working on my Vue project using Vue UI in Visual Studio. Before connecting my API, I wanted to prototype and experiment with fake data. So, I decided to create a JSON file in the assets folder to store my m ...

What is the most efficient way to retrieve a single type from a union that consists of either a single type or an array of types

Is there a way to determine the type of an exported union type by extracting it from an array, as illustrated in the example above? How can this be achieved without directly referencing the non-exported Type itself? interface CurrentType { a: string; b ...

Simultaneously activate the 'onClick' and 'onClientClick' events on an ASP button using JavaScript

I have encountered an ASP button while working on existing code that has both onClick and onClientClick events attached to it. My goal is to trigger both events by generating a click event from an external Javascript file. The line of code I am using for ...

What is the best way to incorporate an "if" statement into my code?

I'm in the process of setting up a section on my website where users can get live price estimates based on a value they input. While I have most of the formula in place, there's one final element that I need to figure out: introducing a minimum f ...

Error in Angular 2: The app.component.html file triggered an exception at line 1, character 108 due to excessive recursion

After successfully setting up the Angular 2 quickstart and connecting to an express server, I encountered a problem when switching from using the template property to component templateUrl. I have created a Plunker to showcase this issue: Plunker Demo imp ...

Ways to resolve the issue of the 'setConfirmDelete' property not being found on type 'JSX.IntrinsicElements' in React.js

index.tsx const setConfirmDelete = (state, close) => { return ( <Modal show={state} onHide={close}> <Modal.Header> <Modal.Title>Title</Modal.Title> </Modal.Header> <Modal.Body> 'T ...

A guide on simulating mouse events in Angular for testing Directives

I am currently exploring the functionality of a column resizable directive that relies on mouse events such as mouseup, mousemove, and mousedown. resize-column.directive.ts import { Directive, OnInit, Renderer2, Input, ElementRef, HostListener } from "@a ...

Popup window displaying website content upon DOM loading, ensuring compatibility across various browsers

I am facing a challenge with my HTML popup window where I need to add text after opening the window using a specific function: var win = window.open('private.php', data.sender_id , 'width=300,height=400'); win.win ...

What's causing me to encounter two canvases while implementing PIXI.js in my Next.js project?

I'm facing a challenge in my game development project that utilizes PIXI.js within a Next.js setup. Currently, I am experiencing an issue where the webpage is displaying two canvases instead of one, leading to unexpected rendering issues and impacting ...

how to change class on vue function result

I need a way to display the content stored in requestData as li elements. Each list item should have an onclick function that, when clicked (selected), adds a specific value from a reference to an array. If clicked again (unselected), it should remove the ...

The range filter is exclusive to the initial controller

My range filter (see code below) is only working on my first controller. I have added the same filter to other controllers in the app.js and HTML, but it's not functioning for some reason. I checked the console for errors, but there are none. Here i ...

What steps are involved in setting up a Typescript-based custom Jest environment?

Currently, I am attempting to develop an extension based on jest-node-environment as a CustomTestEnvironment. However, I encountered an error when trying to execute jest: ● Test suite failed to run ~/git/my-application/tests/environment/custom-test ...

Developing a concealed Repeater element that is retained in the source code for utilization in JavaScript tasks

I am currently working on a setup with two repeaters: one that is displayed when the page first loads, and another that I want to keep hidden until a link called "Add Stuff" is clicked. My goal is to use JavaScript to make this second repeater visible upon ...

Move to the top of the page when the next action is activated

I am working with an Angular 8 application. Within the application, I have implemented navigation buttons for next and previous actions. My goal is to ensure that when a user clicks on the "next" button, the subsequent page starts at the top of the page ...

Having trouble reading the length property of undefined in Angular 7

Seeking to obtain a picture link of the object. The objects are stored in an array and the typescript method looks like this: getMealPicture(orderLineMeal: OrderLine): string { for (let meal of this.meals) { if (meal.id === orderLineMeal.mealId) ...

Access account without providing all necessary identification documents

I'm currently facing an issue with my User Schema, as I initially defined 3 inputs for name, surname, and email. However, I now want to allow users to log in only with their email and password, without having to input their name and surname. How can I ...

Plugin for turning text into "leet speak" using jQuery and Javascript

Recently, I've been on the hunt for a 1337 translator that I can seamlessly integrate into a jQuery plugin. While I believe I'm making progress, I can't shake off the feeling that something's amiss. My gut tells me that what I currently ...