Convert arrays inside arrays into objects by utilizing the keys of each object for the arrays

I am looking to transform the current data structure:

[ { sectionName: 'SectionOne',
    ingredients: [ {ingredient: 'sugar'}, {ingredient: 'flour'} ]},
  { sectionName: 'SectionTwo',
    ingredients: [ {ingredient: 'eggs'}, {ingredient: 'water'} ] },
 ]

into this new format:

{ SectionOne:
       { sectionName: 'SectionOne',
         ingredients: {
           sugar: { ingredient: 'sugar' },
           flour: { ingredient: 'flour' }
          }
        },
{ SectionTwo:
       { sectionName: 'SectionTwo',
         ingredients: {
           eggs: { ingredient: 'eggs' },
           water: { ingredient: 'water' }
          }
        },

 }

In essence, I aim to utilize the object keys from each array to create an object.

An example of the data structure can be found on this jsfddle along with my attempt at achieving this transformation.

Despite trying methods like lodash or vanillaJS, I have only succeeded in converting the outer array. Recursively applying _.mapKeys(), for loops, or similar techniques to reach the desired structure has proven challenging. I believe there may be a simple solution that is eluding me at the moment.

Your assistance on this matter would be greatly appreciated!

Answer №1

To populate an array and create your own objects easily, you can use the map function in JavaScript:

const data = [ 
  { sectionName: 'SectionOne',
    ingredients: [ {ingredient: 'sugar'}, {ingredient: 'flour'} ]},
  { sectionName: 'SectionTwo',
    ingredients: [ {ingredient: 'eggs'}, {ingredient: 'water'} ] },
 ];
 
const res = Object.assign(...data.map(el => ({ // for each element
  [el.sectionName]: {
    sectionName: el.sectionName,
    ingredients: Object.assign(...el.ingredients.map(e => ({[e.ingredient]: e}))) // assign each object within the array
    }
  })))

console.log(res)
console.log(res.SectionOne.ingredients.sugar)

The notation [something] is used to generate a key where the name is the value of the variable something. The spread operator three dots ... splits an array into individual elements as if they were separated by commas.

Answer №2

Check out this efficient solution using the reduce method. There's always room for improvement:

const parts = [
  { partName: 'PartOne',
    items:
      [
        {item: 'hammer'},
        {item: 'screwdriver'}
      ]
  },
  { partName: 'PartTwo',
    items:
      [
        {item: 'nails'}, {item: 'tape'}
      ]
  },
];

const finalResult = parts.reduce((acc, curr) => {
  const itemsObj = curr.items.reduce((accumulator, item) => {
    accumulator[item.item] = {
      item: item.item
    };
    return accumulator;
  }, {});

  var partObject = {
    partName: curr.partName,
    items: itemsObj
  }
  acc[curr.partName] = partObject;
  return acc;

}, {});

console.log(finalResult);

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

Querying MySQL database for variable values in JavaScript

I have a JavaScript file on my website that carries out calculations. Currently, my variables are defined as global variables in another JavaScript file. What I would like to do is make these variables dynamic by pulling their values from a MySQL database ...

I am looking to amalgamate a pair of scripts into a single cohesive work

Currently, I am utilizing jQuery toggleClass to switch CSS styles. $ (".test").click(function () { $(this).toggleClass('active'); }); Whenever I click outside of the Bootstrap menu, the menu gets hidden. In addition to this functio ...

Emails are failing to send through NodeMailer, specifically on the production server

When creating a SMTPtransporter to send emails, I encountered an issue when deploying the code on a server. The code works perfectly fine on my computer with Yarn version '1.22.17'. import * as nodemailer from 'nodemailer'; import * as ...

Searching for a specific element in jQuery by querying a string

I have a situation where an ajax request is made to send text using the POST method to another PHP page. This PHP page then converts the text into markdown format and sends it back. Here's an example of what it looks like: "<p>Meep, meep, <e ...

Utilizing AngularJs to connect server-generated HTML content to an iframe

My Angular app functions as an HTML editor that transmits the template to a server for rendering with dynamic data. The rendered content is then sent back to the client, where it needs to be placed inside an iframe for preview purposes. It appears that ng- ...

Change the ng-model of the initial controller when a button is clicked in a separate controller

I am working on an AngularJS application that has two controllers. I am facing an issue where I need to update the ng-model of an input field in the first controller by clicking a button in the second controller. Accessing the $scope of the first controlle ...

Is it possible for me to transfer a class attribute to a directive template in AngularJS?

I recently came across this directive in AngularJS: productApp.directive('notification', function($timeout) { return { restrict : 'E', replace : true, scope : { type: "@", message: "@ ...

"Step-by-Step Guide: Implementing a Modal Popup Form in Angular with NgBootstrap and FormsModule

I am seeking assistance with my Angular project. I am attempting to implement a Modal Popup Form using NgBootstrap and FormsModule, but encountering issues with the NgbModule not being imported. Here are some details of my setup: node 16.15.1 cli 15.1.5 co ...

Accessing JSON data from an external file using AngularJS's $http method

I am new to Angular and not very comfortable with JavaScript. I am attempting to create an app using the Ionic framework. I have successfully retrieved a list from a JSON file stored in a variable, but now I am trying to use $http.get() to fetch it from a ...

Continuously encountering the 403 Forbidden error when making a POST request to the

My react frontend is running at http://localhost:3000/ and express backend is at http://localhost:8080/ Whenever I attempt to submit the registration form, Chrome console shows an error: 'POST http://localhost:3000/api/users 403 (Forbidden)' ...

Removing a row element from an array

In my current project, I am working on an array named numbers with 4 columns labeled (x), (y), and (z) respectively. The fourth column plays a crucial role in the program. The goal is to remove one of the rows from the main array if two rows have matching ...

Ways to populate a database with information

Is there a convenient way to generate an insert script without having to manually write it out? I'm looking for software with a graphical user interface that allows me to input data and automatically generates the script for me. Currently using Oracle ...

Detecting iFrame Scroll Events

I have been scouring the internet and experimenting with various methods, but I am struggling to detect scrolling of an iframe. The iframe source is located on the same server in the same directory as the page. Below is the initial code I am working with: ...

Ways to designate as not defined or remove specific sections

I've been struggling for hours to figure out how to delete or set to undefined parts of the code below: $(document).ready(function() { // Generate a simple captcha function randomNumber(min, max) { return Math.floor(Math.random() * (m ...

Data input via $_POST method during the submission of a web application is failing to

Having trouble with the login functionality in an EllisLab application framework. The data from the $_POST method is not being stored upon form submission, resulting in an error message. When using var_dump($POST), it shows array(0){}. View Error Screensh ...

Issue: failure of child element - the provided path is incorrect: "users/[object Object]", when implementing Firebase with Next.js

Having trouble with the identityNumber variable, which is giving an error message stating that a string is required. However, my identity number is already a string. Any assistance would be greatly appreciated. Additionally, the aim is to make the identity ...

Expanding mongoDB database by utilizing a Java endpoint using JavaScript

It would be quite impressive if you could provide an answer to my current dilemma. Currently, I am developing a full stack web application that comprises of three main components: A collection of Articles stored in MongoDB A backend developed in Java 8 A ...

Having trouble receiving JSON/JSONP correctly

I've been exploring the world of APIs and I'm facing a roadblock right at the beginning. My goal is to extract data from the Fever Public API in order to retrieve a list of subscribed RSS feeds. The API appears to be straightforward - check it ou ...

Switch the style of a set of thumbnail images when clicked

I am working with a set of thumbnails where one has an "p7_current" class applied, giving it a border, while the rest have an "p7_inactive" class removing the border. My goal is to have the last clicked thumbnail in a group of 6 to have the "p7_current" c ...

The module demoApp could not be instantiated because of an error stating that the module demoApp is not accessible

I am struggling to create a basic Single Page Application (SPA) using Angular and ngRoute/ngView. Unfortunately, I can't seem to get it to work properly. Every time I try, I encounter the error: angular.js:68 Uncaught Error: [$injector:modulerr] Fail ...