JavaScript transforming nested arrays into objects

Need help converting to object

[1, 2, [4, 5, 6], 7, 8, [9, 0], 11, 12]

Desired output:

{
  1: 1,
  2: 2,
  'array1': {
    4: 4,
    5: 5,
    6: 6
  },
  7: 7,
  8: 8,
  'array2': {
    9: 9,
    0: 0
  },
  11: 11,
  12: 12
}

Actual output received is: { 1: 1, 11: 11, 12: 12, 2: 2, 7: 7, 8: 8 }

This is my code:

input = [1,2,[4,5,6],7,8,[9,0],11,12];
obj = {}

const convert = (arr) =>{
for (i = 0; i < arr.length; i++){
    if(!Array.isArray(arr[i])){
        obj[arr[i]] = arr[i];
    }
    
 }}
    convert(input);
    console.log(obj);

Answer №1

Here's my personal perspective:

const data = [1,2,[4,5,6],7,8,[9,0],11,12];

const transform = arr=>{
  let n=0;
  return arr.reduce((a,c,i)=>{
    if (Array.isArray(c)) a["array"+(++n)]=transform(c);
    else                  a[c]=c;
    return a}, {})
 }
 console.log( transform(data) );

Answer №2

Transform Using For Each

data = [1, 2, [4, 5, 6], 7, 8, [9, 0], 11, 12];
resultObj = {}
const transformUsingForEach = (array) => {
    let counter = 0;
    array.forEach(item => {
        if (Array.isArray(item)) {
            counter++;
            item.forEach(subItem => {
                if (!resultObj[`array${counter}`]) {
                    resultObj[`array${counter}`] = {};
                }
                resultObj[`array${counter}`][subItem] = subItem;
            });
        } else {
            resultObj[item] = item;
        }
    })
}
transformUsingForEach(data);
console.log(resultObj);

Convert Using Reduce

const data = [1, 2, [4, 5, 6], 7, 8, [9, 0], 11, 12];
let objResult = {}
const convertUsingReduce = (arr) => {
    let count = 0;
    return arr.reduce((acc, element) => {
        if (Array.isArray(element)) {
            acc[`array${++count}`] = convertUsingReduce(element);
        } else {
            acc[element] = element;
        };
        return acc;
    }, {})
};
objResult = convertUsingReduce(data);
console.log(objResult);

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

Use Jquery to retrieve the innerhtml content

Hey there! I'm currently in the process of learning Jquery and have encountered an issue with accessing form elements. My script is designed to open a div and then fill it with a predefined HTML form. To achieve this, I'm using ajax to fetch the ...

Incorporating Event Listeners for Controlling Playback and Navigation in HTML5 Video

I am trying to integrate an HTML5 video into my website to demonstrate how a product works. Each time a user clicks on an image, I want the video to skip to a specific time and then pause at another predefined time. However, the code I have implemented so ...

PHP script only inserting the first element of an array into the MySQL database table

When attempting to capture up to 15 entries upon submission, the code provided is only capturing the initial entry in the database. Additionally, an error message is being displayed, stating: An error in the SQL syntax has occurred. Ensure to refer to the ...

Symfony2: Making AJAX request that unexpectedly returns complete html page

I am facing an issue with setting up a basic AJAX request in Symfony2. It appears that the controller is not receiving the request as expected. Instead of displaying '123', the AJAX response shows the HTML content of the current page (index.html. ...

Discover the underlying data within a nested JSON structure and track back to identify the corresponding values

In the JSON structure provided below, Suppose I have the chapter "number" and section "number". What is the most efficient way to search and trace backwards starting from what I already know, in order to find the "number" of the title within titles and t ...

Seeking assistance with transmitting data to the server and retrieving it for use. I am looking to achieve this goal utilizing JavaScript with Node.js

I've been experiencing challenges with the interactions between front-end and back-end. I am confident that I am sending the data, but unfortunately, I am unable to access it afterwards. Recently, I utilized this code template (sourced from Mozilla&ap ...

Change the behavior of an onclick event on the second click

I'm trying to make a button on my website that not only plays music when clicked but also changes the text inside the button to "Go to SoundCloud" and redirects to SoundCloud. Currently, I have been able to achieve both functions separately - redirect ...

The ReactJS code has been compiled without errors, but it is not displaying in the browser

After putting in a significant amount of effort, I successfully managed to install and configure ReactJS. Upon running the "npm start" command, the code was "COMPILED SUCCESSFULLY" and directed me to the web browser. However, there was no output visible; t ...

Display all elements in a MySQL JSON field array

My database includes a JSON field where post tags are stored. id:1, content:'...', tags: ["tag_1", "tag_2"] id:2, content:'...', tags: ["tag_3", "tag_2"] id:3, content:'...', tags: ["tag_1", "tag_2"] I am looking to creat ...

Conceal anchor tag depending on the destination URL

Is there a way to hide anchor tags that point to a specific URL? I am aware of how to do so based on the id using JavaScript: document.getElementById('someID').style.display = 'none'; <a href="#" id="someID" style="display: none"& ...

Guide to utilizing AJAX to retrieve a value from a controller and display it in a popup

I need assistance with retrieving data from a controller and displaying it in an HTML pop-up when a button is clicked. Currently, the pop-up shows up when the button is clicked, but the data is not being loaded. I would like the values to be loaded and d ...

What steps can I take to resolve my password validation rule when confirming during sign-up?

Utilizing react-hook-form in combination with Material-UI for my sign-up form has been a challenge. I am currently working on implementing a second password field to confirm and validate that the user accurately entered their password in the initial field, ...

Can a photo frame app be created using PhoneGap?

I'm looking to develop an application where I can capture a picture, crop the face of a person, and then embed this face into a frame. Is there a solution using PhoneGap for this task? Can anyone provide some ideas on how to get started? Thank you i ...

Analyzing the string's worth against the user's input

I need help figuring out how to save user input on a form (email and password) as variables when they click "Register", so that the data can be used later if they choose to click "Login" without using default information. I am working on this project for s ...

Animation loading on React.js when the page or URL is changed

Just starting out with React and trying to incorporate a loading animation when the page/url changes on button click - check it out here: https://codesandbox.io/s/cthululel-7zmsl?fontsize=14 Successfully got the animation working on initial load, but runn ...

Using v-model with the input type files in Vue.js allows for easy two

Is there a way to retrieve data from v-model array in an input type of "file" that allows multiple selections? <input type="file" multiple v-model="modFiles[index]"> <input type="file" multiple v-model="modFiles[index]"> <input type="file" ...

Tips for creating an expression within ng-if

I am struggling with placing an expression inside ng-if that needs to be assessed in order for my content to be shown based on its outcome. This is what I currently have: <a ng-if="abc.status===failure" href="http://localhost:3000/abc/abc">image< ...

Utilizing jQuery's .done() and .fail() methods to handle

Our goal here is to control the outcome of the createSite function. If it returns {ac:failed}, then the .fail(failOption) will be triggered; otherwise, the sendMail or .done(sendMail) function will be executed while still retaining the data from the crea ...

Start the process by initializing a std::unique_ptr in the same way as a raw array pointer

For my current OpenGL project, I am working on creating an array on the heap using the following code: float* vertices = new float[48] { 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, // front top right, 0 0.5f, -0.5f, 0.5f, 0.0f, 1.0f, 0.0f, // fr ...

`I'm encountering issues when trying to pass an array through localStorage into a new array`

This is a complex and detailed question that I am struggling to find a solution for. Despite using deprecated mysql due to hosting limitations, the problem lies elsewhere. Part 1 involves dataLoader.php, which queries the database and retrieves posx and p ...