Guide on transforming an array into a collection of objects

Could someone please help me with converting this array?

const myArr = ['lorem', 'ipsum', 'dolor', 'sit', 'amet']

I want to transform it into an object structure like this:

{
  lorem:{
    ipsum:{
       dolor:{
         sit:{
           amet: ''
         }
       }
     }
   }
 }

Is there a simple method to achieve this transformation?

Answer №1

let output = myArr.reduceRight((a, b) => {
  return {
    [b]: a
  };
}, '');

You have the option to simplify the syntax:

let output = myArr.reduceRight((a, b) => 
  ({[b]: a}), '');

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

Ways to modify the final sum exclusively for a single table

I am currently struggling to figure out how to calculate only the grand total of the first table using just one jQuery/JavaScript script. The code I am referencing is from: Below is the code snippet: <!DOCTYPE html> <html xmlns="http://www.w3 ...

Ways to ensure the axios call is completed before proceeding with the codeexecution

I need to use axios to send a request and retrieve some data that I want to pass as a prop to a React Component. Here's my render function: render() { boards = this.fetchBoardList(); return ( <div className="app-wrapper"> ...

How can I showcase array elements using checkboxes in an Ionic framework?

Having a simple issue where I am fetching data from firebase into an array list and need to display it with checkboxes. Can you assist me in this? The 'tasks' array fetched from firebase is available, just looking to show it within checkboxes. Th ...

Checkbox change cannot be initiated

Using jQuery version 1.8.3, I am attempting to trigger a state change for each checkbox. The following code works when placed inside a click event: $("#btn_off").click(function(){ $( "tr td input" ).each(function( index ) { if ($(this).is(":ch ...

Are the commands overlapping?

Currently, I am in the process of developing a dynamic discord chat bot using JavaScript and node.js. One of my goals is to implement a specific command without interfering with an existing one. The bot functions flawlessly across all servers where it is ...

Conditionally defining variables in JavaScript only if they are currently undefined

I have been working on extracting two keywords from a URL in the following format: localhost:3000/"charactername"/"realmname" My goal is to extract "charactername" and "realmname" and assign them to variables. Here is the code snippet I am using: var c ...

Retrieve the JSON Object containing JSONArray values with a null key

I need assistance in extracting the null key value from this JSON Object. The value 'null' is stored as a JSONArray, and I am looking to iterate through it to access the values. Visit this link for more information ...

Wait for the reaction from react router history to go back

After clicking the submit button in a form, I need to navigate backwards using history.goBack. However, if there is no previous page in the history, I want to redirect to a screen displaying a thank you message using history.replace. const handleSubmit = ( ...

What is the best way to deactivate a button using AngularJS?

$scope.date = moment(currentDate); $scope.date1 = moment(currentDate).add(-1, 'days'); function checkDate(){ if ($scope.date > $scope.date1) { return true; } else{ return false; } }; checkDate(); ...

In the year 2021, eliminate linked documents using mongoose/MongoDB middleware

After extensive research on stack overflow, I attempted various solutions for deleting referenced documents in MongoDB using node.js. Unfortunately, most of them either utilize deprecated methods or simply do not function as expected. Within my applicatio ...

Retrieving detailed information from MongoDB in a Node.js environment

I am currently developing a nodejs server using mongoDB. I have some sample data that looks like this: { "_id": ObjectId("555f1c0c7f4b820758b439b0"), "user": "Guest1", "friend": [{ "myfriend": "Guest2", "in ...

Removing the switcher outline in Bootstrap Switch: a step-by-step guide

I have implemented the bootstrap-switch - v3.3.1, however, I want to remove the default blue outline that appears around the switcher when toggling it on or off. Despite setting style="outline: 0 none; for the input, the outline remains visible. Below is ...

Encountering a problem when trying to create a node in Neo4j using Node.js

Here is my code for a Node.js application using Neo4j: var neo4j = require('neo4j-driver').v1; var express = require('express'); var logger = require('morgan'); var path = require('path'); var bodyParser =require(&a ...

Is it possible to apply fog to a specific area in Three.js instead of being dependent on the distance from

Picture this: a vast THREE.PlaneGeometry representing the floor with a camera placed at an arbitrary spot within the scene. By manually adjusting the near and far values of the fog, I can effectively conceal the outer edges of the plane to create the illu ...

Frequent running of jQuery scripts

In my jQuery ajax code, I created a FitnessPlanDay: // Add Day ajax $('#addDay').on("click", function() { $.ajax({ url: '@Url.Action("AddDay")', type: 'POST', ...

Perform multiple function invocations on a single variable using JavaScript

Is there a way to execute multiple functions on a single object in JavaScript? Maybe something like this: element .setHtml('test'), .setColor('green'); Instead of: element.setHtml('test'); element.setColor('gre ...

PHP, utilizing the mysqli function to work with arrays

I am currently learning how to work with PHP and MySQL. Within my database, I have a table named user_entries which consists of two columns: max_val and num. To extract these two columns and analyze them using the function numberTimesOver, I wrote a code ...

Tips for shuffling the sequence of EJS variables

I am currently working on creating a quiz that consists of multiple choice questions. In order to display the Question, Correct Answer, and 3 other wrong options, I am utilizing EJS variables. The format will be similar to the following example: Question: ...

Remembering previous scroll position with jScroll upon revisiting page

I'm implementing infinite scrolling of products on our site using jQuery jScroll. Can anyone guide me on how to save the scroll position when the user returns to the homepage? Appreciate any assistance! ...

Setting a consistent theme or style for all HTML/React tags using a selector inside a specific component

Here's a simplified example of what I'm trying to do: I'm using Material UI Styles for styling my components. I want to style all the <Link> tags in my component. For instance: const useStyles = makeStyles(theme => ({ menuLink: ...