Transform three sets of arrays into a complex hierarchical structure

My goal is to develop a complex nested structure by combining elements from three arrays.

var obj; 
obj = [
    {
        "a": {
            "A" : "aA",
            "B" : "aB",
            "C" : "aC"
        }

    },
    {
        "b": {
            "A" : "bA",
            "B" : "bB",
            "C" : "bC"
        }

    },
    {
        "c": {
            "A" : "cA",
            "B" : "cB",
            "C" : "cC"
        }

    },      
]

To achieve this, I have three arrays as follows:

var arr1 = ["a","b","c"]
var arr2 = ["A","B","C"]
var arr3 = [["aA","aB","aC"],["bA","bB","bC"], ["cA","cB","cC"]]

I am wondering if there are any straightforward approaches using lodash or ES6. Even though my current method involves another function that generates 'arr3' from 'arr1' and 'arr2', what other methods can be used to create multi-level nested objects from multiple arrays? Is there any available documentation on this topic for handling more than 3 arrays?

This is what I have attempted so far:

arr1.forEach((item)=>{
    arr2.forEach((prop)=>{
        obj[item] = {}
        obj[item][prop] =  prop
    })
})

Answer №1

Give this code a shot:

  let array1 = ["apple", "banana", "cherry"];
  let array2 = ["Apple", "Banana", "Cherry"];
  let array3 = [["aA","aB","aC"],["bA","bB","bC"], ["cA","cB","cC"]];
  let objectArray=[]; //initialize empty object array
  for (let i=0; i<array1.length; i++){ // loop to create outer objects
    let innerObj = {}, sampleObject={};
    for (let j=0; j<array2.length; j++) { // loop to create inner objects
      innerObj[array2[j]] = array3[i][j]; // create inner objects like {"Apple":"cA","Banana":"cB","Cherry":"cC"}
    }
    sampleObject[array1[i]] = innerObj; // assign inner object as value of outer object
    objectArray.push(sampleObject); // push outer object to the object array
}

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

utilize the useRef hook to display the total number of characters within a text area

Introducing the following component: import React from 'react'; export interface TexareaProps extends React.TextareaHTMLAttributes<HTMLTextAreaElement> { maxLength?: number; id: string; } export const Textarea = React.forwardRef( ( ...

What is the best way to obtain a direct file link from a server URL using JavaScript?

After acquiring a file located at /home/johndoe/index.html, I am utilizing a tool like XAMPP to host, with the folder /home being hosted on localhost. The variables in play are as follows: $server_addr = "localhost"; $server_root = "/home"; $file_dir = " ...

Struggling to implement AJAX into a Rails application for updating comments, but encountering difficulties as the JavaScript file is not running in the

I am currently implementing AJAX in my Rails application to prevent the page from refreshing and scrolling back to the top whenever a new comment is added to an object. Instead, I want it to refresh and stay in the same position on the page. To test wheth ...

Using PHP to convert an array of SQL rows into a JSON encoded format

I am facing difficulties in converting a PHP array generated from an SQL query to a JSONObject using json_encode. I am utilizing Google Volley for connection. When dealing with a single row result, everything works fine, but when there are multiple rows, ...

What is the best way to display a unique image in a div based on the size of the

Being new to web design, I have a question about creating a webpage with a large image in the center like on GitHub's Windows page. How can I work with the image inside that particular div or area based on different screen sizes? Is it possible to mak ...

Obtaining the date for the previous month using JavaScript or jQuery

I need to retrieve a specific date in JavaScript. My goal is to obtain the current date based on a variable named frequency, which can have values of Daily, Weekly, or Monthly. if(frequency=="daily") { date='current_date -2 days'; } e ...

MongoDB's $set operator is mistakenly interpreting an array index as an object index

When working with MongoDB, it appears that the $set paths containing numerical components are interpreted as object keys instead of array indexes if the field has not been previously created as an array. > db.test.insert({_id: "one"}); > db.test.upd ...

Establishing the bottom limit for the vertical axis on a column chart with the Visualization Google API

I am currently working on implementing the Google Chart API alongside AngularJS. I attempted to adjust the min property of the vertical axis for my column chart to 0 using the following code: var dataMois = CaDuMois.query(function(){ $scope.comparat ...

Adjusting the prototype of a JavaScript object in real-time

Is there a way to dynamically change object prototype in JavaScript in order to fully recover an object previously saved using JSON, including its behavior? Currently, one solution is to create a new object and copy the data from the JSON-recovered object ...

Guide to organizing information by date within subdocuments in an array in mongodb

Here is the structure of my document: _id: "adklkj389723jk23KLJjl2LU92kJO387" "impressions": [{ "_id": ObjectId("5b74799535f2722494075981"), "country": "GB", "impression_count": 22, "_campaignid": ObjectId("5b72d78847db422040ee60cf"), ...

Switch between showing or hiding at least three divs

I'm currently using a simple script that toggles the visibility of two div elements: <script type='text/javascript'> $(window).load(function(){ function toggle_contents() { $('#page1').toggle(); ...

Issue with AngularJs in locating links based on rel attribute is unresolved

When I attempt the following: $document.find('link') The output shows: JQLite(9) [link, link, link, link, link, link, link, link, link] However, if I try: $document.find('link[rel="canonical"]') or $document.find('link[rel= ...

I'm having trouble figuring out how to properly paginate data from Firebase without running into errors. Can

Here is the code I have written: <nav v-if="(tasks.length >= 7)" aria-label="Page navigation example"> <ul class="pagination fw-bold justify-content-center"> <li class="page-item"> ...

Unlocking the Power of res.render in SailsJS's beforeCreate and afterCreate Functions

I am facing a challenge where I need to access the res.render function within the beforeCreate hook to render an html template. However, it seems that the res object is not passed to this particular function. Any suggestions on how I can achieve this? Bas ...

Transaction response for embedded iFrame with Accept.js on Authorize.net

I've recently integrated authorize.net accept.js embedded iFrame into my application, but I'm facing difficulties in setting the transaction response in my lambda function to retrieve the expected data. Although I've checked similar queries ...

Remove all keys of type BaseType from objects that are children of BaseType

There are two types: BaseType and BabyType. export type BaseType = { id: string } export type BabyType = BaseType & { name: string }; In a generic layer where <T extends BaseType> is used, the item being dealt with is actually a 'B ...

Dynamic buffer geometry featuring morph attributes fails to refresh the shadow animation

Recently, I revamped the MD2 code within the library to utilize THREE.BufferGeometry instead of THREE.Geometry, resulting in a significant reduction in memory usage. The process involved converting the model to THREE.BufferGeometry post-loading and making ...

Passing a JavaScript parameter into a RAZOR function from the CodeBehind

I am facing an issue with my code. I need to pass the value of a JavaScript variable X as a parameter in the Razor function EXTENDED.ProcessDay() function Test() { var X = document.getElementById("targetID").value; documen ...

What is the best way to incorporate a <c:forEach> loop into JSP operations?

I am attempting to calculate the product of two variables that are associated with an item in a loop. Below is the code snippet from the JSP file: <table> <thead> <tr> <th>PRICE</th> <th ...

Is it possible to dynamically change a form's input value using a JavaScript keyup function based on input from other form elements?

My form utilizes the keyup function to calculate the total value of 3 input fields by multiplying them and displaying the result. Below is a fiddle showcasing this functionality: $(document).ready(function () { $(".txtMult1 input").keyup(multInp ...