Is it possible to convert an array into an object?

I'm attempting to restructure an array of objects into a new object where the label property serves as the key for multiple arrays containing objects with that same label.

Check out this JSBin function I created to map the array, but I'm unsure about the ES6 logic required to achieve the desired output.

https://jsbin.com/foyijisaku/1/edit?js,console

original array

var originalArray =

    [
      {
        'id': 6,
        'label': 'hello'
      },
      {
        'id': 5,
        'label': 'hello'
      },
      {
        'id': 4,
        'label': 'bye'
      },
      {
        'id': 3,
        'label': 'bye'
      },
      {
        'id': 2,
        'label': 'bye'
      },
      {
        'id': 1,
        'label': 'bye'
      }
    ]

new object

var newObject =

    {
        'hello': [
            {
                'id': 6,
              'label': 'hello'
            },
            {
                'id': 5,
              'label': 'hello'
            },
        ],
        'bye': [
            {
                'id': 4,
              'label': 'bye'
            },
            {
                'id': 3,
              'label': 'bye'
            },
            {
                'id': 2,
              'label': 'bye'
            },
            {
                'id': 1,
              'label': 'bye'
            },
        ]
    }

Answer №1

const initialArray = 
    [
      {
        'id': 6,
        'label': 'hello'
      },
      {
        'id': 5,
        'label': 'hello'
      },
      {
        'id': 4,
        'label': 'bye'
      },
      {
        'id': 3,
        'label': 'bye'
      },
      {
        'id': 2,
        'label': 'bye'
      },
      {
        'id': 1,
        'label': 'bye'
      }
    ]

const newObject = initialArray.reduce(function(accumulator, current) {
  accumulator[current.label] = accumulator[current.label] || [];
  accumulator[current.label].push({
    id: current.id,
    label: current.label
  });
  return accumulator;
}, {})

Using the ES6 spread operator:

const newObject = initialArray.reduce((accumulator, current) => {
  accumulator[current.label] = accumulator[current.label] || [];
  accumulator[current.label].push({...current});
  return accumulator;
}, {})

The reason for not directly pushing 'current' is to avoid maintaining a reference.

Answer №2

To process every element in the array, you need to use a loop like for...in.

var newObject;
for(var o in originalArray){
    if(o.label == 'hello'){
        var len = object['hello'].length;
        object['hello'][len] = o;
    }else{
        var len = object['bye'].length;
        object['bye'][len] = o;
    }
}

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

Transitioning to Firebase Authentication

I made the decision to transition away from firebase authentication. To accomplish this, I exported all firebase users along with their email addresses, hashed passwords, salt keys, and other necessary information. Next, I transferred them to a database a ...

Issue with nested promises not functioning as anticipated within a for loop

I'm currently facing an issue with extending a Promise inside a .then() block. My goal is to update records in the database using a for-loop and then close the database after all updates have been processed. However, the application is exiting abruptl ...

Error message in the browser console: Uncaught TypeError - The function allSections.addEventListener is not recognized

Whenever I inspect my browser console, I keep encountering this error: Uncaught TypeError: allSections.addEventListener is not a function at PageTransitions (app.js:16:17) at app.js:33:1 I find it strange because my VS Code editor does not display any err ...

What is the process for extracting all data members and fields from an object in Java?

Is there a way to retrieve all member functions and fields defined in an object in Java? I want the ability to pass any object and have it print out all of its methods and fields along with their values. For instance, how does a JSON par ...

"Facing rendering issues with handlebars.js when trying to display an

I have been diligently working on trying to display an array from my running express app, but despite the lack of errors, nothing is being rendered. Take a look at my handlebars template: <h3>Registered Users:</h3> <h5>{{users}}</h5& ...

Is it simple to host a vue.js web application within the assets folder of a sails.js project?

Currently, I am in the process of learning how to utilize Sails.js and vue.js. My goal is to develop a small application where a vue.js application is situated within the assets/ directory of Sails.js. The challenge I'm facing is figuring out how to s ...

jQuery drag and drop for more than one object

I am in the process of building a web-based file browser using jQuery and PHP. One of the tasks I need to accomplish is the ability to select multiple files/folders and drag them into another folder. My research so far indicates that jQuery UI's drag ...

Error in Angular: Unable to Access Property '..' of null

Having an issue with my Angular project where I keep getting an error message saying "cannot read property of '...' of undefined" whenever I select an employee from the combo box. The '...' represents the index of the selected employee. ...

Issue arose when attempting to remove an item from an array within React

I have a handleAd function that adds new components to an array, and I also have a handleDelete function that is supposed to remove the selected element from the array. I am generating unique keys for each element to prevent deletion issues. Initially, th ...

Tips for displaying a specific array in react JS using the map function

Hello everyone, I am currently working on creating a hotel webpage using React.js and I'm focusing on developing the facilities page. My goal is to display the description of the facilities based on the button that the user clicks. How can I achieve t ...

Personalized sorting to match the unique rendering of cells in Material UI Data Grid

I have integrated the Material UI V4 Data Grid component into my React Js application. The Data Grid component requires two props: rows (list type) and columns (list type). Below is a sample row item: const rows = [ { id: 1, customerName: " ...

Learn the simple steps to duplicate events using ctrl, drag, and drop feature in FullCalendar v5 with just pure JavaScript

My goal is to incorporate CTRL + Drag & Drop functionality in FullCalendar v5 using nothing but pure JavaScript. I delved into the topic and discovered that this feature has been discussed as a new UI feature request on the FC GitHub repository. There ...

Positioning of Responsive Slider

I'm currently working on a responsive website, but I am facing challenges with the placement of the slideshow dots. When I switch to the device toolbar, they seem to change position. I have tried various methods such as using relative and absolute uni ...

The implementation of CORS headers does not appear to function properly across Chrome, Firefox, and mobile browsers

I encountered an issue while trying to consume a third party's response. The functionality works correctly in Internet Explorer, but fails in Chrome, Firefox, and on my mobile browser. Despite searching online and testing various codes, I continue to ...

External IPs cannot access Node.js

I am facing an issue with my Amazon EC2 Server where I have set up a node js server. It is not accessible from the outside using the public DNS, but it can be accessed from the same instance (localhost). Any assistance in resolving this problem would be gr ...

Is there a way to incorporate arguments into my discord.js commands?

Hey there! I'm looking to enhance my Discord commands by adding arguments, such as !ban {username}. Any tips or guidance on the best approach for this would be amazing! const Bot = new Discord.Bot({ intents: ["GUILD_MESSAGES", "GUIL ...

I am encountering an issue where the msal-browser login process seems to be frozen at the callback

After successfully installing the msal-browser package, I am able to log in. However, I encounter an issue where the screen gets stuck at the callback URL with a code. The samples provided in the GitHub repository demonstrate returning an access token in ...

Real-time update of quiz results based on varying factors

In my quiz, I have set up variables that start at 0 and increase based on certain conditions. One variable should increase when a question is answered correctly, while the other should increase when a question is answered incorrectly. If you answer a quest ...

Add HTML and JavaScript code dynamically with JavaScript

Currently, I am working on a project that involves an HTML table with some basic JS interactions triggered by user clicks. The structure looks something like this: htmlfile.html ... ... position action ...

Using an interface with PolymorphicJsonAdapterFactory in Moshi: Tips and Tricks

I have a scenario in my model where I am working with an interface that has two concrete types, and I want to serialize/deserialize them using Moshi. However, I am unsure if the PolymorphicJsonAdapterFactory is the right approach for me. After reviewing sa ...