Recursive method used to create an object by looping through an array

I'm really struggling with this algorithm. It needs to be recursive, but I can't seem to crack it. Any help would be greatly appreciated. Thank you!

Here is the problem: ['a','b','c',['d','e','f',['g','h']], [i, j, k]]

Desired Output:

{
  a: true,
  b: true,
  c: true,
  d: {
   e: true,
   f: true,
   g: {
     h: true
   }
  },
   i: {
     j: true,
     k: true
   }
}

Answer №1

To convert an array to an object, you can utilize the Object.fromEntries method by providing key/value pairs. If the "key" is actually an array, extract the first element as the key and recursively process the rest of the array to generate the corresponding value:

const toObject = arr =>
    Object.fromEntries(arr.map(item => Array.isArray(item)
        ? [item[0], toObject(item.slice(1))]
        : [item, true]
    ));

const arr = ["a", "b", "c", ["d", "e", "f", ["g", "h"]], ["i", "j", "k"]];
const result = toObject(arr);
console.log(result);

Answer №2

Here is an example of using the Array#reduce method:

const transform = (arr = []) =>
  arr.reduce((acc, elem) => {
    if (Array.isArray(elem)) {
      const [key, ...rest] = elem;
      acc[key] = transform(rest);
    } else {
      acc[elem] = true;
    }
    return acc;
  }, {});

console.log(
  transform(["apple", "banana", "cherry", ["date", "elderberry", "fig", ["grape", "honeydew"]], ["imbe", "jackfruit", "kiwi"]])
);

Answer №3

In Ruby (imagine this as a simplified code).

def convert(arr)
  arr.each_with_object({}) do |element, hash|
    case element
    when String
      hash[element.to_sym] = true
    else # Array
      hash[element.first.to_sym] = convert(element.drop(1))
    end
  end
end

Imagine a scenario (slightly altered from the original example)

arr = ['a','b','c',['d','e','f',['g','h', ['m', 'n']]], ['i', 'j', 'k']]

The output will be:

convert arr
  #=> {
  #     :a=>true,
  #     :b=>true,
  #     :c=>true,
  #     :d=> {
  #       :e=>true,
  #       :f=>true,
  #       :g=>{
  #         :h=>true,
  #         :m=>{
  #           :n=>true
  #         }
  #       }
  #   },
  #   :i=>{
  #     :j=>true,
  #     :k=>true
  #   }
  # }

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

Text gently appearing and disappearing within a block

I’m looking to create a smooth fade effect for the content inside a block that is being dynamically changed by script. Instead of an instant change, I want the old content to fade out and the new content to fade in gradually without using jQuery — just ...

Notifying a Child Component in React When a Props-Using Function Resolves a REST Call

When I submit an item or problem, I trigger a function in the parent component that has been passed down to the child component as props. After sending my information, I want to clear the input fields. The issue is that I am clearing the input fields immed ...

Using javascript to save the contents of a textbox as cookies, then displaying the result

I am a beginner in the world of JavaScript and I am looking for an easy solution. Can someone please guide me on how to store the values entered in two text boxes on one HTML page, and then display them on another HTML page? ...

Run the command "node index.js" to simultaneously start and stop the server

After installing WSL2 and the Ubuntu 22.04 distribution on Windows 11, I set up my environment, installed nvm, Node version 16.17.1, and then ran npm init in my folder. Following that, I installed Express and created an index.js file with a simple structur ...

JavaScript first, middle, and last names

When working with Javascript, I have encountered a challenge. I am attempting to extract the First, Middle, and Last names from a full name input into three separate fields - Character Length, Middle Name, and Initials. At this point, I have successfull ...

Is there a way to specifically retrieve the number of likes or followers from Facebook, Twitter, Instagram, and Snapchat in order to display them on my HTML website?

Can you provide guidance on how to obtain the total numbers of likes or followers for our Facebook, Twitter, Instagram, and Snapchat pages without including the plugin boxes or buttons? We are solely interested in the actual numbers. Would this be feasibl ...

A Guide to Displaying HTTP Error Messages on the Angular Login Page

When encountering a form validation failure on my login page, I utilize ngMessage to display an error message. However, I now want this div to be displayed in the event of an HTTP 500 error. While I can retrieve the corresponding error message when an HTTP ...

Are browser notifications for deciding actions no longer functioning in javascript and vue.js?

Even though I'm utilizing a library named vue-native-notification, the functionality should be similar to regular native notifications. I am interested in adding actions to my notifications, such as: Someone is calling you -> answer/decline The is ...

send parameter when clicking a link rather than using a hashtag

One interesting feature on my website is a menu link with the attribute title=.roc. When this link is clicked, I want to extract this attribute and click on an element with the same attribute on the destination page. Let's consider a scenario where I ...

The error message "TypeError: scanner.js is undefined and property 'scan' cannot be read" is occurring

I've been attempting to incorporate scanner-js into my react application, but I keep encountering the error TypeError: Cannot read property 'scan' of undefined. The code snippet is provided below: import { scanner } from 'scanner-js&ap ...

Saving the index.html file to disk when the button is clicked

Is there a way to export the current HTML page to a file? I have attempted to achieve this using the following code, but it only works when the page is loaded and not with a button click. <?php // Start buffering // ob_start(); ?> <?php file_pu ...

What are the steps for creating a rectangular container and placing an object within it?

Is there a way to display both the box and object inside the box using three.js? I attempted to achieve this by creating a cubeGeometry: var cubeMaterials = new THREE.LineBasicMaterial({wireframe:true,wireframeLinewidth:8,} ); var cubeGeometry = new THRE ...

The code functions correctly when executed in the console, however, it encounters issues when

My code runs correctly in the console but produces incorrect results in Hackerank Issue: Determine the count of all substring palindromes within a given string function isPalindrome(str) { var len = str.length; var mid = Math.floor(len / 2); for ...

Attempting to utilize Vue js to connect to an API

I'm currently facing difficulties while trying to access an API in order to retrieve data. As a novice in the world of vue.js and javascript, I encountered an error message saying Uncaught SyntaxError: Invalid shorthand property initializer. Unfortuna ...

Warning: An unhandled promise rejection has occurred due to a TypeError, as the property 'title' cannot be read since it is undefined

I am encountering an error related to the router.post("/") function in my JavaScript, express, ejs, and MongoDB project. The main objective of this post request is to enable users to save a blog post, which will then redirect them to the main page ("/"). ...

Adding a function into a node within PostgreSQL

Hi there, I'm currently following a tutorial and attempting to execute a simple insert query, however, I keep encountering a 404 error. I am using Postman to input values. function function insertUser(req, res, next){ req.body.users = parseInt(r ...

Is there a way to transform standard JSON data into a format that can be interpreted by Google Visualization

Recently, I delved into the world of Google charts and was amazed by its capabilities. However, I encountered a hurdle when trying to integrate data from a SQL server view. To tackle this issue, I initiated a sample project to facilitate the process but ha ...

How can the service-worker and cache storage API handle caching a redirect with an HTTP 302?

I need help with my website that is served over https from Tomcat and includes a service worker for fetching and storing resources in the cache. Everything works well when Tomcat is running, but I have run into an issue. My Tomcat configuration includes ...

The discrepancy between the values of sys.getsizeof() and nbytes in a Numpy array with dtype object is quite significant

I have a dataset containing names in a csv file with 2 columns and 200 rows each. Both columns contain random names. The code snippet below loads the csv file into a pandas Dataframe, converts it into a numpy array, and then into a standard python list: x_ ...

Failed Ajax request due to SyntaxError: JSON parsing error with unexpected input at position 0

I am struggling to successfully execute a call to my controller from the view using an Ajax Post method. Below is the ajax call: var Model = { Ration: "123", Batch: "2323", Ingredien ...