Create a nested object or dictionary in JavaScript by recursively combining a group of arrays

I'm feeling a bit puzzled trying to figure out a solution for this particular problem.

So, I have a series of arrays and the goal is to create a JSON-like object based on them.

For example:

[a]
[a, b]
[a, b, c]
[a, b, d]
[e]
[e, f]
[e, f, g]

should turn into

{
  a: {
    b: {
      c: {}
      d: {}
    }
  }
  e: {
    f: {
      g: {}
    }
  }
}

and so forth.

What I aim to achieve is:

  1. Start with an empty object, let's call it Dictionary
  2. Take any array of length n
  3. Go through the array one by one, so that at position i, if Dictionary doesn't have a property from Dictionary[Array[0]]...[Array[i]], I create that property with value Array[i]: {}

The issue I'm facing is figuring out the dynamic path to the desired property. I'm not sure how to construct a multi-level path to the property name I need. For example, when i === 0,

var check = Array[i];
typeof Dictionary[check] === 'undefined';

This will give the expected outcome. However, it will create all the properties as flat object properties instead of nested dictionaries.

Then, I struggle to add the next step to the check variable --

...
check = check[Array[i+1];

check = Dictionary[check][Array[i+1]]

and trying further variations doesn't seem to work.

I'm sure I might be overlooking something obvious here, but I'm stuck and would appreciate any insights anyone might have.

Additionally, if possible, I need to accomplish this using only jQuery or lodash, as plain JS might not be a viable option.

Answer №1

Simple:

list = [
    ['x'],
    ['x', 'y'],
    ['x', 'y', 'z'],
    ['x', 'y', 'w'],
    ['q'],
    ['q', 'r'],
    ['q', 'r', 's']
];


tree = {};
list.forEach(function(elem) {
    elem.reduce(function(node, letter) {
        return node[letter] || (node[letter] = {});
    }, tree);
});

document.write("<pre>" + JSON.stringify(tree, 0, 3))

Answer №2

Your response is more concise, but I had already completed it...

var arrays = [
    ['a'],
    ['a', 'b'],
    ['a', 'b', 'c'],
    ['a', 'b', 'd'],
    ['e'],
    ['e', 'f'],
    ['e', 'f', 'g'],
    ['e', 'f', 'g', 'h', 'i'],
    ['e', 'f', 'g', 'h', 'j']
];

var dict = {};

arrays.forEach(function (item) {
    addToArray(dict, item);
});

document.getElementById("output").innerText = JSON.stringify(dict, null, 3);

function addToArray(dictionary, array) {
    array.forEach(function (item) {
        dictionary = addNode(dictionary, item);
    });
    return dictionary;
}

function addNode(node, item) {
    return node[item] || (node[item] = {});
}
<pre id="output"></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

Leveraging the power of MKL-optimized numpy.dot() for efficient computation with 3-dimensional

I have been working on optimizing my code for quite some time now, and recently discovered a significant performance decrease when using numpy.dot with arrays containing 3 or more dimensions. For instance, consider this code: def ti(): r = random.rand( ...

Utilizing promise values within asynchronous functions

I know this question has been asked multiple times, but I'm facing a situation where I need to retrieve a variable created within a promise. The examples I've come across involve using .then to access the data, but in my case, I need to work with ...

Tooltips will display on all Nivo charts except for the Nivo Line chart

I'm having an issue with nivo charts where the tooltip isn't showing up for my line chart. Even after copying and pasting the example from here: Other chart examples work fine with tooltips appearing, but for some reason, it's just not work ...

Challenges arise in compiling JS with webpack due to spread syntax complications within an npm package

In my code, I have a class called AnalyticsService with methods for logging analytics events to Google Analytics and Kentico. When trying to reuse this code in different projects by importing it from an npm package, I encountered a compile error related to ...

Modifying two distinct charts according to the choices made in two independent dropdown menus

In my current project, I am facing a challenge with integrating two separate dropdowns containing UFC fighter names. The goal is to display a plot showing the KD (Knockdown) data for the selected fighters over time when their names are chosen from both dro ...

PHP, jQuery, and MySQL combine to create a powerful autocomplete feature for your

I've implemented the source code from into my project, but I'm facing an issue where I can't retrieve any results when typing in the autocomplete textbox. Could someone point out where I might be making a mistake? This is the code I am us ...

Autocomplete component fails to trigger onChange event upon losing focus in Mui framework

When using a Mui Autocomplete with the properties of multiple and freeSolo, a situation arises where pressing Return triggers an onChange event. However, when tabbing out of the Autocomplete widget, the typed text remains without updating the state of the ...

What are some effective methods for troubleshooting npm modules?

Typically, the process involves installing React with yarn/npm install react and then using it by importing React from 'react' Imagine you need to debug a React source code, so you clone a GitHub repository. But how do you incorporate this sour ...

The click() function in jQuery executing only once inside a "for" loop

This is an example of my HTML code: <!DOCTYPE html> <head> <title>Chemist</title> <link href="stylesheet.css" rel="stylesheet"> </head> <body> <h2 id="money"></h2> <table border="1px ...

What is the best way to retrieve the Json data in React Native as indicated in the following example?

The data in JSON format follows a specific pattern. This JSON data is received from the backend through an API call and stored in a state variable. { "message": "user created successfully", "status": "success", "student": { "class": "1 ...

Securing $_FILES Filenames in PHP

I have a form with an "attachments" field where users can add multiple attachments. Before uploading each attachment, I use a function to make the file name safe. Here is the function: function safeFile($file) { $lower = strtolower($file); $trim ...

Tips for managing pagination in a Single Page Application

Within my Single Page Application (built with Javascript and AngularJs), I have an items list that is paginated, displaying 10 items per page. To ensure that the user's current pagination remains intact even when navigating to other pages, I store th ...

What is the best way to perform an AJAX request in Typescript with JSON data?

Currently, I am delving into the realm of AJAX and encountering some hurdles when attempting to execute an AJAX request with parameters. Specifically, I am facing difficulties in sending JSON data: My approach involves utilizing Typescript in tandem with ...

Can we utilize conditions to both select and deselect items using JavaScript and PHP together?

I have a selection list with checkboxes that is dynamically generated based on certain conditions in the code snippet below. if ($data_inteiro_01 <= $data_inteiro_02) { if ($parcela[$i] === 0) { $display = 'disabled'; } } els ...

Form submission requires a checkbox to be checked

I have been searching for a way to make checkboxes required. Is there a method similar to using required="required"? Currently, I generate my checkboxes in the following manner and would really appreciate any guidance on this topic. It's crucial for m ...

Best practices for uploading an array of objects (multiple image files) using Node.js

Encountering an issue in my application where I need to upload multiple photos. The object consists of motherPhoto, fatherPhoto, spousePhoto, and siblingsPhoto: { "mothername": "kerin", "motherPhoto": "C:/fakepath/mot ...

Validating user input fields to display error messages when empty

As part of my program, I need to gather information from users regarding their name and the number of pets they have. If a user enters an empty string, I want to display an error message prompting them to input something and fill the text box with their en ...

Converting HTML table data into a JavaScript array

On my website, I have an HTML table that displays images in a carousel with their respective positions. The table utilizes the jQuery .sortable() function to allow users to rearrange the images by dragging and dropping. When an image is moved to the top of ...

Phonegap application functioning smoothly on computer, encountering issues on mobile device

Hey there! I recently developed a phonegap app that retrieves JSON data from a YQL link and presents it to the user. It works perfectly on Google Chrome desktop, but my client mentioned that it doesn't work on his Android 2.3 device. Could you help me ...

How about this: "Can you turn a picture into text with just one click?"

Seeking assistance to enhance the 'About Us' page on our website. Each team member has a profile with their email address listed below, but we want to add a picture that disappears when clicked, revealing the email address in its place. You can ...