How to utilize the map function in JavaScript to generate an associative array

I have an array of objects with the following structure

[{'list': 'one', 'item': 1},
 {'list': 'one', 'item': 2},
 {'list': 'one', 'item': 3},
 {'list': 'two', 'item': 1},
 {'list': 'two', 'item': 2}]

Now I need to reformat it as shown below

[{'one': [1, 2, 3]},
 {'two': [1, 2]}]

What is the most efficient way to achieve this transformation using the Array.map function?

Answer №1

If you want a solution, consider using Array.prototype.reduce. This method allows you to specify a return value in the callback function for the subsequent call.

var exampleData = [
        { 'group': 'alpha', 'value': 1 },
        { 'group': 'alpha', 'value': 2 },
        { 'group': 'alpha', 'value': 3 },
        { 'group': 'beta', 'value': 1 },
        { 'group': 'beta', 'value': 2 }
    ],
    transformedData = exampleData.reduce(function (result, current) {
        result[current.group] = result[current.group] || [];
        result[current.group].push(current.value);
        return result;
    }, {});

document.write('<pre>' + JSON.stringify(transformedData, 0, 4) + '</pre>');

Answer №2

Answering your specific query:

// Assuming x is the variable holding your array of objects.

result = {}; // Initialize an empty object to store the output

x.forEach(function (element) { // Utilize this method to loop through each element in the list
    result[element.list] = result[element.list] || [];   // Taking inspiration from Nina Scholz's solution mentioned below
    result[element.list].push(element.item);   // Add the outcome to the array
 });

Answer №3

If you need to group elements in an array based on multiple properties, a group-by method is what you're after. Take a look at this helpful answer for guidance:

Here's the code snippet:

function groupBy(array, f)
{
  var groups = {};
  array.forEach(function(o)
  {
    var group = JSON.stringify(f(o));
    groups[group] = groups[group] || [];
    groups[group].push(o);
  });
  return Object.keys(groups).map(function(group)
  {
    return groups[group];
  })
}

var result = groupBy(list, function(item)
{
  return [item.lastname, item.age];
});

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

Objects for requesting and responding

When utilizing express.js, middlewares have the ability to modify both the request object and the response object. This raises the question: what exactly do these request and response objects represent, and what information do they hold? ...

Mobile Image Gallery by Adobe Edge

My current project involves using Adobe Edge Animate for the majority of my website, but I am looking to create a mobile version as well. In order to achieve this, I need to transition from onClick events to onTouch events. However, I am struggling to find ...

Modify JSON from using single quotes to double quotes using JavaScript

Received a JSON from the backend to the front end that uses single quotes throughout, causing issues with a Magento 2 widget. The JSON structure is as follows: { 'mood': 'happy', 'reason': 'why shouldn't I?'} T ...

What is the best way to utilize the spread operator across several Vuex modules?

In my search for a solution, I came across another post suggesting that this approach would be effective. However, despite implementing it, I encountered the following error message: 'TypeError: Cannot convert undefined or null to object' comput ...

Picture disappearing following the refresh of an AJAX iframe

Currently, I am developing a profile system where the user's profile is displayed in an iframe that reloads when the form submit button is clicked. The content updates successfully upon reloading, but there is an issue with images not displaying after ...

Toggle the visibility of a table column based on user selection in Vue.js

I am having issues with displaying and hiding based on checkbox click events. Can anyone assist in identifying the mistake? When clicking on an ID, it should hide the ID column. Similarly, clicking on "first" should show/hide based on checkbox clicks, and ...

When the div element reaches the top of the page, it sticks to the top and is only displayed when the user

In the center of a full-screen hero section, there is a form. When it reaches the top, its position becomes fixed and additional classes are added through a script - such as shrinking its height and adding a background. What I aim to achieve is for the fo ...

Center the span in CSS by setting its position to absolute

I am trying to create a span element positioned as absolute inside a div. The div has top and left values set. When the user inputs text, the span expands with the given text towards the right to contain it. However, I would like it to grow symmetrically o ...

Creating a new component when a click event occurs in React

Currently diving into the world of React while working on a project that involves mapbox-gl. I'm facing an issue where I can successfully log the coordinates and description to the console upon hover, but I can't seem to get the popup to display ...

Ways to monitor the status of a server request using jQuery (ajax)?

I am currently working on a PHP application that involves users submitting forms to the server via ajax (jQuery). The server needs to insert a large number of records into a MySQL database, which may take some time due to various calculations. My question ...

What is the best way to access the names of iframes and frames within window.length?

I am currently working on a project with numerous frames. While I am aware that using window.length will provide the number of "child browsing contexts", like frames and iframes, I am unsure how to access a list of these frames and view their names. Is t ...

Redirecting in Next.js without the use of a React component on the page

I need to redirect a page using HTTP programmatically only. The following code achieves this: export const getServerSideProps: GetServerSideProps = async (context) => { return { redirect: { destination: '/', permanent: false, ...

beforeSend method in jquery ajax synchronously calling

One of my functions is called: function callAjax(url, data) { $.ajax( { url: url, // same domain data: data, cache: false, async: false, // use sync results beforeSend: function() { // show loading indicator }, ...

What steps do I need to take to incorporate the Google API into my Chrome extension's content script

I am currently attempting to display labels using the Gmail API within a content script. Below are snippets from my manifest.json and content-script.js files: { "name": "Append Test Text", "description": "Add test123 to body", "version": "1.0", "p ...

Getting the value of "Page=?" from the href attribute in an HTML tag can be done using Selenium Webdriver and Java

I am looking to extract the value "page = ?" from a specific "href" tag in the HTML code below. I need this value for my Selenium WebDriver script so that my loop can iterate up to page 53. Can someone guide me on how to retrieve the "page =" value mentio ...

Performing a bulk create operation with Sequelize using an array

I am facing a task where I have an array of items that need to be created in the database. My approach is to check each insertion for success. If successful, I will add the item with a flag indicating success as true in a new array (results) in JSON forma ...

What is the best way to approach conducting unit tests for JavaScript code?

When it comes to unit testing JavaScript and jQuery, what is the best approach? Which frameworks do you recommend using? Do these frameworks seamlessly integrate with build tools like CI, Maven, and others? We would love to hear about your personal expe ...

Guide on implementing Vuetify Component Slot Function

Can someone help me figure out how to implement the v-alert dismissible component with additional functionality when the close button is clicked? According to the documentation, there is a function called toggle in the close slot that allows you to "Toggle ...

Could someone break down for me the behavior exhibited within this method?

Hello there, I'm a beginner so please forgive me for any lack of knowledge. const example = { myFunction(){ console.log(this); }, myFunction2(){ function myFunction3(){ console.log(this) } return ...

Outputting exceptional elements of array in C

After creating a function to generate an array of random values and another function to extract unique values from that array, I encountered an issue with printing the correct values. Despite the algorithm correctly counting unique values, the output was i ...