Guide to transforming a JavaScript array into an object following a defined format

Can someone assist me with transforming the array structure in logicData to the format of object in returnObject?

I am looking for a function that can take the logicData array and return an object in the format specified below.

Furthermore, I also need to be able to recreate the original logicData array using the returned object. Any help would be greatly appreciated. Thank you!

// array
var logicData = [
  {
    details: {
      name: "User-1",
      id: 1,
      age: "38",
    },
    company: "XYX",
    position: "Accountant",
  },
  {
    details: {
      name: "User-2",
      id: 2,
      age: "55",
    },
    company: "XYX",
    position: "Sales executive",
  },
  // additional objects omitted for brevity
]

Desired object format:

// required object format
const returnObject = {
  first: {
    details: {
      name: "User-1",
      id: "1",
      age: "38",
    },
    company: "XYX",
    position: "Accountant",
  },
  second: {
    first: {
      details: {
        name: "User-2",
        id: 2,
        age: "55",
      },
      company: "XYX",
      position: "Sales executive",
    },
    // additional nested objects omitted for brevity
  }
}

Answer №1

To transform data structures like logicData into returnObject, you can utilize the following function:

function convertArrayToObject(array){
    let result = array[array.length - 1];
    for(let i = array.length - 1; i > 0; i--){
        result = {
            first: array[i - 1],
            second: result,
        }
    }
    return result;
}

convertArrayToObject(logicData);

And to revert structures like returnObject back to an array structure like logicData, this function can be helpful:

function revertObjectToArray(object){
    const result = [];
    let temporary = object;
    while("second" in temporary){
        result.push(temporary.first);
        temporary = temporary.second;
    }
    result.push(temporary);
    return result;
}

revertObjectToArray(returnObject);

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

Basic asynchronous JavaScript and XML (AJAX) call

I am currently learning about ajax and experimenting with a script that involves extracting information from a JSON object and displaying it on the document. Below is an example of the JSON file named companyinfo.json: { 'id':1, 'name&apos ...

Multer is successfully retrieving images, but unfortunately, it is failing to save the files in the intended directory

I am currently facing an issue with my Express server. The problem arises when a user attempts to make a post request for their profile, including a profile picture submission. I have set up Multer to handle the image upload process and store the photo in ...

The dark mode feature in my Mac project is essential. I am currently leveraging Next.js alongside React and TypeScript

Struggling to implement dark mode in my Mac project. Utilizing Next.js with React and TypeScript, but can't seem to get it right. I've attempted the following methods without success. Any suggestions? const config: Config = { plugins: [ re ...

Encountering Issues with File Uploads in Express.js with Multer

Currently, I am immersing myself in Node.js through the guidance of a book titled "Web Development with Nodejs and MongoDB." However, I have hit a roadblock when attempting to upload an image using Multer. The code snippet causing me trouble is as follows: ...

Setting a TypeScript collection field within an object prior to sending an HTTP POST request

Encountered an issue while attempting to POST an Object (User). The error message appeared when structuring it as follows: Below is the model class used: export class User { userRoles: Set<UserRole>; id: number; } In my TypeScript file, I included ...

Troubleshooting: Issues with Custom Image Loader in Next.js Export

I'm encountering a problem while attempting to build and export my Next.JS project. The issue lies with Image Optimization error during the export process. To address this, I have developed a custom loader by creating a file /services/imageLoader.js ...

Tips for merging JSON outputs

How can I merge this JSON result? The problem arises when trying to combine this data in Codeigniter, resulting in a fatal error: Call to a member result_array() $this->alerts ->select('products.id as productid, products.code as co ...

How can I retrieve the results of an SQLite call in HTML5 without passing them to a separate function?

How can I use SQLite in HTML5 to execute a call like the one below, so that the result is returned immediately rather than passed off to another function? try { mydb.transaction( function(transaction) { transaction.executeSql( &apo ...

Utilize an internal TypeScript module without explicitly referencing it

Imagine I have the following setup: List.ts: module Helper { export class List{ } } Parser.ts: module Helper { export class Parser { } } Now, when working with another module, I find myself constantly needing to use "Helper.List" e ...

How can I organize the method functions of a class in separate files in JavaScript?

Is there a way to separate and organize the code of each method into individual files? This will help keep the code clean, simple, and easier to maintain. Currently, my structure looks like this (minimal reproducible example): // there is also a parent ...

Enabling or disabling a button dynamically in Ionic based on a conditional statement

I am looking to dynamically enable or disable buttons based on specific conditions. The data is retrieved from Firebase, and depending on the data, I will either enable or disable the button. For example, if a user passes the First Quiz, I want to enable ...

The value of the jQuery data on click event handler becomes 'undefined' when used within an AJAX handler

When I click on the Positive or Negative buttons, a jQuery event handler function is triggered. Each button passes different data objects to the handler. However, within the AJAX POST handler, I am unable to access the data from the click event. $('# ...

Making @types compatible with TypeScript 2.1 in Visual Studio 2015 Update 3

The potential of TS 2.x @types is intriguing, but I'm struggling to make it work effectively! I'm using Visual Studio 2015 - version 14.0.25431.01 Update 3 My TypeScript version for Visual Studio 2015 is 2.1.4, downloaded from this link The VS ...

Encountering an issue while trying to initiate a fresh React Native Project

As I work through the setup steps outlined in the React Native Documentation on my M1 MacBook Pro, I encounter a stumbling block. Despite successfully running React projects and Expo projects on this machine before, I hit a snag when trying to create a new ...

Tips for resolving the chakra-ui theme issue with loading input background

I've been working on applying a theme to my Next.js app using chakra-ui, but I've been facing an issue that I can't seem to resolve. Currently, when the /form route is loaded, the theme is set to light. After changing it to dark, the theme i ...

How can JSON data size be minimized effectively?

We have encountered an issue with high throughput on some of our data stores. Our current approach involves serializing POJOs to JSON using Jackson, but we are looking for alternative methods to compress the JSON data. Initially, we considered using BSON ...

Utilizing a Promise in NodeJS and Express to effectively capture the writing functionality of the HTTP module

Currently, I am in the process of developing an Express application with the following components: NodeJS v8 express (latest version) As I delved into the workings of the onHeaders module and observed how it alters the HTTP headers, I became keen on lev ...

Is it possible to utilize a global constant in Angular without the need for injection into the controller?

I have defined a constant object in coffeescript: angular .module 'main', [] .constant 'CONFIG', IMAGEROOT: 'http://some-img.s3-website-ap-southeast-1.amazonaws.com/' When using the constant in html, I write it like ...

"Utilizing Ajax for Form Validation in Zend Framework 2 - Is it

After following a tutorial, I encountered an issue with my code. The tutorial I followed can be found at the following link: I need help resolving the problem in my code. When I submit the form, the function to validate and save the data is being called ...

Google Bar Graphs Cannot Display Decimal Values

Having an issue with my bar chart from Google Chart not displaying float numbers. Other types of bar charts provided by Google Chart work fine, but this specific type doesn't show the float numbers. Here is the code I have written: http://jsfiddle.ne ...