Transform array elements into objects with associated indices and data types

Looking for assistance in restructuring this array to meet specific formatting requirements. Struggling to achieve the desired result on my own. The parent key should be named "type" and the subparent key should have a value of "category". Any suggestions or guidance would be greatly appreciated.

Suggesting beautifying the code for better visualization as it might not display properly here...

[{
    "Labour": {
      "Cleaners": {
        "unitCost": 3409.5,
        "markupValue": 18,
        "totalCost": 3643.5
      },
      "Plumber": {
        "unitCost": 309.0909,
        "markupValue": 0,
        "totalCost": 309.0909
      }
    }
  },
  {
    "Material": {
      "Cleaners": {
        "unitCost": 450,
        "markupValue": 5,
        "totalCost": 475
      },
      "Plumber": {
        "unitCost": 450,
        "markupValue": 5,
        "totalCost": 475
      }
    }
  },
  {
    "Other": {
      "Report Fee": {
        "unitCost": 180,
        "markupValue": 0,
        "totalCost": 180
      }
    }
  }
]

[{
    "type": "Labour",
    "category": "Cleaners",
    "unitCost": 3409.5,
    "markupValue": 18,
    "totalCost": 3643.5
  },
  {
    "type": "Labour",
    "category": "Plumbers",
    "unitCost": 3409.5,
    "markupValue": 18,
    "totalCost": 3643.5
  },
  {
    "type": "Material",
    "category": "Cleaners",
    "unitCost": 450.5,
    "markupValue": 0,
    "totalCost": 5
  },
  {
    "type": "Material",
    "category": "Plumbers",
    "unitCost": 450.5,
    "markupValue": 0,
    "totalCost": 5
  }
]

Answer №1

Utilizing the Array.prototype.flatMap() and Array.prototype.flat() methods, you have the capability to transform multi-dimensional arrays into a single-dimensional array as shown below.

const input = [
  {
    "Labour": {
      "Cleaners": {
        "unitCost": 3409.5,
        "markupValue": 18,
        "totalCost": 3643.5
      },
      "Plumber": {
        "unitCost": 309.0909,
        "markupValue": 0,
        "totalCost": 309.0909
      }
    }
  },
  {
    "Material": {
      "Cleaners": {
        "unitCost": 450,
        "markupValue": 5,
        "totalCost": 475
      },
      "Plumber": {
        "unitCost": 450,
        "markupValue": 5,
        "totalCost": 475
      }
    }
  },
  {
    "Other": {
      "Report Fee": {
        "unitCost": 180,
        "markupValue": 0,
        "totalCost": 180
      }
    }
  }
];

const output = input.flatMap((item) => {
  return Object.entries(item).map(([type, value]) => (Object.entries(value)
    .map(([category, subValue]) => ({
      type,
      category,
      ...subValue
    }))
  ));
}).flat();
console.log(output);

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

Utilize jQuery to automatically assign numbers to <h1-h6> headings

Looking to develop a JavaScript function that can automatically number headings (h1- h6) for multiple projects without relying on CSS. Currently achieving this with CSS: body { counter-reset: h1; } h1 { counter-reset: h2; } h2 { counter-reset: h3; } ... T ...

attempting to fulfil a promise through a resolution

I am currently attempting to use a resolve with a promise in response to an issue with filters that I am currently tackling. However, my resolve function is not yet functioning as expected. I have decided to implement this approach based on advice I recei ...

What is the process for manually extracting nested arrays from a JSON file and transforming them into nested arrays within a data model?

After embarking on my Swift learning journey, I encountered a challenge. I found myself needing to utilize the Alamofire framework and manually parse data from a JSON file into a data model. The JSON file in question contains a nested array, and despite my ...

How can dynamic x and y values be used to create moving waves on Canvas in HTML5?

My dynamic array values consist of x and y... Incorporating these x and y values, I want to create varying sine, triangular, square, and sawtooth waves on an HTML5 canvas... ...

NetSuite - Custom Fields - Linked to Address Book but Inaccessible through JavaScript

Currently in the process of creating a Sales Order script to extract a custom field linked to the chosen shipping address. While I have successfully retrieved all address fields (such as city and zip), I am facing challenges when attempting to access any c ...

Having trouble with npm global installation? Encountering the error message "Error: EACCES: permission denied

As the administrator of my MacBook, I am facing an issue while trying to run a npm command in my Django project. It is refusing to run due to missing permissions. (venv) jonas@Air-von-Jonas salaryx % npm install -g sass npm ERR! code EACCES npm ERR! syscal ...

Issue with cancel button click in Jquery confirm window not being resolved

I have been encountering issues with opening a confirmation dialog in JavaScript despite having the code in place. The dialog is supposed to have 'yes' and 'no' options. function ConfirmDialog(obj, title, dialogText) { if (!dialogC ...

Preset for Typescript in Babel 6

Can anyone help me find a Babel preset for Typescript that is compatible with Babel 6, rather than Babel 7? I've been searching for this module with no luck. Is it possible that the TS preset is not supported for Babel 6? ...

What are the best practices for securely storing SSL certificates and public/private keys?

I possess keys that appear like this. MIID0DCCArigAwIBAgIBATANBgkqhkiG9w0BAQUFADB/MQswCQYDVQQGEwJGUjET MBEGA1UECAwKU29tZS1TdGF0ZTEOMAwGA1UEBwwFUGFyaXMxDTALBgNVBAoMBERp bWkxDTALBgNVBAsMBE5TQlUxEDAOBgNVBAMMB0RpbWkgQ0ExGzAZBgkqhkiG9w0B CQEWDGRpbWlAZGltaS5mcjA ...

Is it possible that bitwise left shifts in JavaScript ES6 (<<) become cyclical after surpassing a shift of 63?

From my understanding of the << bitwise left operator in JS (ES6), the void to the right is typically filled with zeros. However, through observation in both V8 and JSC, it appears that the set bits suddenly reappear when we shift by 64 or more. (2 ...

Use jQuery to retrieve the response from a JSON request and showcase it on the existing HTML page

Currently, I am working on a project that involves integrating a JSON-based web service from a remote server. The method of this service can be accessed by using specially formatted URLs such as: http://root-url/ws/service-name?request={json-string} The ...

Browsing a Table in Vue

I'm currently building a Vue application that showcases a collection of quotes and includes a search feature for filtering through the data. It seems like I might not have properly linked the function to the correct element. I've added a v-model ...

Determining the Existence of a Specific Bot within a Guild | Utilizing discord.js

Hey there! I've got a bot that needs to collaborate with two other bots. I'm looking for a way to check if one of the bots is already in the guild. If it's not, I want to prompt the user to invite it. Here's what my code currently look ...

Unstyled Cards Failing to Receive Design

I am currently working on creating a prototype that utilizes two Bootstrap 4 cards to display information from a form and store related information from another form in the second card. The current layout of this setup can be observed below: https://i.sst ...

Searching for object in array using NodeJS with specific key value

Is there a way to retrieve an object from an array based on the value of one of its keys? Consider the following array: var arr = [ { city: 'Amsterdam', title: 'This is Amsterdam!' }, { ...

Using React to manipulate objects within an array

I am looking to convert a firebase object into an array, with the desired structure shown below: For a working example, check out this JSFiddle link: https://jsfiddle.net/vfra1yp5/ 0: Object { first: "https://google.com", last: "google" ...

ScopeKey fails to function properly within the Nuxt.js auth module

As I delved into learning the ins and outs of Nuxt.js, I encountered a challenge while working with its Auth module. After successfully logging in, my goal was to verify the scope of the accounts. I attempted to achieve this by utilizing the "scopeKey" pr ...

Show a button using CSS when the cursor is hovering

Expressing my gratitude to everyone! I need assistance with implementing a function in reactJS where the <button /> remains hidden during page loading and reveals itself when hovered over. Despite trying various methods, I have been unable to resolve ...

What is the method for specifying a specific sub-dependency version in a package in Node.js?

Let me simplify my issue for you. I am facing troubles while trying to install two plugins, plugin A version 2.0 and plugin B version 3.0. It turns out that plugin B has plugin A as a sub-dependency with a conflicting version, resulting in a build phase e ...

Loop through the ng-repeat scope object in AngularJS

Is it possible to create rows of 3 using bootstrap and ng-repeat with data from a scope object without the loop repeating every three times due to ng-if? I am curious if something like <h4> {{yogurt[$index+1].name}} </h4> would work. Below is ...