I am looking to generate an object using an array that contains nested subarrays as well

Below is the input data:

const arr =  [10,20,[40,50,60],70,80,[90,100],111,112];

The desired output is as follows:

{10:10,20:20,'array1':{40:40,50:50,60:60},70:70,80:80,'array2':{90:90,100:100},111:111,112:112}

Answer №1

My method involves utilizing the Array.prototype.reduce() function, but it is only capable of handling arrays with a single level of nesting.

const arr =  [10,20,[40,50,60],70,80,[90,100],111,112];
let count=1;

let a = arr.reduce((acc,curr) => {

    if(Array.isArray(curr)){
    let b = curr.reduce((acc1,curr1)=> {
        acc1[curr1] = curr1;
      return acc1
    },{})
    acc[`array${count}`] = b;
    count+=1;
  }
  else{
    acc[curr] = curr;
  }
 
  return acc;

},{})

console.log(a)

As the output is an object, the order may not necessarily match the input array structure.

Answer №2

To simplify the process, iterate through the array and create a new object along the way:

let count = 1;
let newObj = {}

arr.forEach((item) => {
  if(Number.isInteger(item)){
    newObj[item] = item;
  } else {
    subObj = {}
    item.forEach((subItem) => subObj[subItem] = subItem);
    newObj[`array${count}`] = subObj;
    count += 1;
  }
})

Answer №3

Check out this recursive solution using reduce(), which can handle deeply nested arrays as well.

function extractArrayValues(array){
    let arrayCounter = 0;
    return array.reduce((result, current) => {
        if (!Array.isArray(current)) result[current] = current;
        else { 
            arrayCounter += 1;
            result[`array${arrayCounter}`] = extractArrayValues(current);
        }
        return result;
    }, {})
} 

const sampleArray = [10, 20, [40, 50, 60], 70, 80, [90, 100], 111, 112];
console.log(extractArrayValues(sampleArray));

const nestedArray = [10, 20, [40, 50, 60], 70, 80, [90, 100, [40, 50, 60]], 111, 112];
console.log(extractArrayValues(nestedArray));

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

Tips for successfully capturing the click event within the WowBook interface

Currently utilizing the WowBook plugin and looking to intercept the click event on the page turning link. Specifically, I am aiming to redirect the user to a different URL when they reach the end of the "pages" (div containers). Despite my efforts in the ...

What steps do I need to take to ensure that this Regex pattern only recognizes percentages?

I am attempting to create a specific scenario where I can restrict my string to three digits, followed by a dot and two optional digits after the dot. For example: 100.00 1 10.56 31.5 I've developed a regex pattern that allows me to filter out any ...

Is it possible for the values to change based on where the parameter is located within the function?

Why do functions produce different results when the parameter order is changed? For instance: Code Sample #include <stdio.h> #define MAX_SIZE 100 void sum2(float *list, int n); void sum3(int n, float *list); float input[MAX_SIZE]; int main(void){ ...

The function Rotate() does not exist

Within my project, I have set up a canvas where I am able to: Load an image onto the canvas Resize the uploaded image Currently, I am working on implementing a rotate function that allows me to rotate the loaded image within the canvas by holding down th ...

A concept to consider is the passing of a character array by reference within

For a school assignment, I am working on finding the longest line in a piece of code. I have encountered a puzzling situation where the "longest_line" variable prints correctly within the while loop but not outside of it. int main() { int ch; char ...

What is the best way to retrieve data from a database by utilizing a select option and displaying it in an input box?

Code to retrieve data from a database: public function getOneByName($name){ try{ $link = DB_Helper::createMySQLConnection(); $query = "Select * From vendor Where vendor_name=?"; $stmt = $link->prepare($query); $stmt->bindVal ...

What is the best method for choosing the next item with jQuery?

I am facing an issue while trying to apply some design on the next element. The error message that I am encountering is: Error: Syntax error, unrecognized expression: [object Object] > label Below are my selections for browsing by category: BROWSE BY ...

Forwarding to another page following an AJAX post request to a Django view

I've been struggling to get this basic piece of code to work properly, despite trying numerous resources. I can't seem to pinpoint where I'm going wrong. Essentially, I have a javascript function submitData() that is supposed to make an ajax ...

Is it optimal to count negative indexes in JavaScript arrays towards the total array length?

When working in JavaScript, I typically define an array like this: var arr = [1,2,3]; It's also possible to do something like: arr[-1] = 4; However, if I were to then set arr to undefined using: arr = undefined; I lose reference to the value at ...

Finding the count of childNodes within a div using Selenium

I've been grappling with this issue for the majority of today; I'm trying to tally up the number of childNodes within a parent div. It's essentially mimicking a list where each childNode represents a row that I want to count. The HTML struct ...

Modify website styling using JavaScript to edit external CSS/SCSS files

I am looking to 'modify' a file that is stored on my server, for example: <link rel="stylesheet" href="css/plugin.scss"> Not only that, but I also want to specifically edit a line within the SASS file. In SASS, you can declare variables i ...

Exploring the fundamentals of AngularJS in changing content within a directive

My HTML code snippet is structured as follows: <custom-logo> <div> <img src="logo.png"> </div> <custom-logo-after> </custom-logo-after> </custom-logo> I'm working on modifying the cus ...

What does the `$add` feature do in AngularJS?

Just diving into the world of angularJs, I find myself faced with the challenge of upgrading an app from version 0.9 to 1.0.5. The function '$add' called on an array has me stumped. Despite hours of searching through documentation, I still can&ap ...

Verify if the specified value exists in the array, locate its position, and then pass an intent with additional data to the following activity fragment on Android

Looking into a similar question that was posted on StackOverflow - How to check if a value exists in an array in Android In my FragmentActivity, I have 3 arrays set up as follows: String[] productName = {"Bread", "Butter", "Cadburry", "Tin Spinach", ...

Is it best practice to use the AngularFirestoreCollection for updating Firestore items in AngularFire?

Within my application, I have a list that necessitates the use of an "or" condition. However, according to the documentation: "In this case, you should create a separate query for each OR condition and merge the query results in your app." Consequently ...

Create PDFs using PhantomJS when the HTML content is fully loaded and ready

I am a newcomer to utilizing phantomjs and encountering difficulties in rendering my website as a PDF file. Although I can successfully render a simple version of the page, issues arise when multiple images and web fonts are involved, causing the DOM not t ...

Tips for assisting flow with managing the initialization of react component state

In my React components, I am initializing state like this: export default class LoginForm extends Component { state = { // (*) flash: { message: null, style: null } // initialiser for flash message: show no ...

Error encountered: Node Express Postgres application failing due to a syntax error in

Encountering an issue while attempting to pass variables to a PostgreSQL database: Error: syntax error at or near "," const rb = req.body; const sql= "insert into test1 (user, name, created) values (?, ?, CURRENT_TIMESTAMP);" poo ...

React css modules to enhance styling in your web project

I am in the process of incorporating a CSS module into the login component. Currently, I have a style.css stylesheet located in the src/styles folder, which is responsible for loading global styles. However, I now want to customize the login component by a ...

Display inner div upon button click in Wordpress

After clicking a button, I want to load a div and not have it load on page load. I specifically mentioned loading the div after clicking the button, not just showing it. The code is working, but I need help implementing it in WordPress. <div id="cont ...