Can .map() be utilized to transform an array of objects into a single object?

Presented here is a subset of data extracted from a larger dataset in a project:

const data = [
                { scenario: '328', buckets: 2 },
                { scenario: '746', buckets: 1 },
                { scenario: '465', buckets: 2 }
            ];

The task at hand involves restructuring the data into an object where the scenario value serves as the key and the bucket value as the corresponding value, illustrated in this format: https://i.sstatic.net/PZLD6.png

I managed to accomplish this goal using .forEach method like this:

const reformattedData = {};
            data.forEach(o => {
                reformattedData[o.scenario] = o.buckets;
            });

However, I am under the impression that there might be a more succinct way to achieve the same result. My attempt with .map was as follows:

const reformattedData = data.map(o => ({ [o.scenario] : o.buckets}));

Unfortunately, this approach does not produce the desired outcome. Instead, it yields [{328: 2}, {746: 1}, {465: 2}]. What adjustments are required in the .map() version to obtain the intended result?

Answer №1

To transform the data and generate an object from the entries, you can use Object.fromEntries.

const
    data = [{ scenario: '328', buckets: 2 }, { scenario: '746', buckets: 1 }, { scenario: '465', buckets: 2 }],
    result = Object.fromEntries(data.map(({ scenario, buckets }) =>
        [scenario, buckets]
    ));

console.log(result);

Another approach involves using spread objects with Object.assign.

const
    data = [{ scenario: '328', buckets: 2 }, { scenario: '746', buckets: 1 }, { scenario: '465', buckets: 2 }],
    result = Object.assign(
        {},
        ...data.map(({ scenario, buckets }) => ({ [scenario]: buckets }))
    );

console.log(result);

Answer №2

One approach is to utilize the reduce() function

const examples = [
   { category: 'A', value: 22 },
   { category: 'B', value: 16 },
   { category: 'C', value: 30 }
];
const result = examples.reduce((accumulator, {category:c, value:v}) => ({...ac, [c]:v}), {});
console.log(result)

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

Utilizing a Chrome packaged app to interact with a local sqlite database through reading and writing operations

Is it feasible to access and manipulate a local sqlite database from within a Chrome packaged app? I am currently able to work with a locally stored JSON file for my app data, but now I also require the functionality to interact with a sqlite database in ...

Shuffle contents of a Div randomly

I'm currently in the process of developing a new website and I need to randomly move the news feed. To achieve this, I have created an array containing the list of news items. The array is then shuffled and placed within the news feed section. Althou ...

The Ajax script seems to be failing to update the PHP file along with its corresponding variable value

I have a simple form where upon clicking the "=" button, I want the calculated value to be displayed in file process.php. However, this functionality is not working for me. It seems that when the "=" button is clicked, nothing happens. The default value in ...

Alas, an error has occurred with eslint npm. The elusive 404 Not Found reared its head once more when attempting to access the es

I'm currently in the process of organizing my JavaScript code and preparing to transition to TypeScript. I recently set up node.js, npm, and eslint on my Ubuntu 20.04 system. After doing so, I executed npm -init and eslint -init. $ npx eslist util.js ...

Leveraging the local variables within a function in conjunction with the setTimeout method

Currently, I'm facing an issue with a website that I'm working on. I have created a function that should add a specific class to different ids in order to make images fade out one by one on the home page. To streamline the process, I used a local ...

What is the best way to showcase the outcomes of arithmetic calculations on my calculator?

In the midst of creating a calculator, I have encountered some issues in getting it to display the correct result. Despite successfully storing the numbers clicked into separate variables, I am struggling with showing the accurate calculation outcome. l ...

Ensuring that an added row remains at the bottom of a table composed of rows generated dynamically by utilizing the .detach() method

I need to ensure that the "subtot" row is always appended as the last row in the table. When dynamically adding rows, the "subtot" row appears as the last row the first time, but does not stay at the bottom when more rows are added. Even though I want the ...

Sending Emails with AngularJS

Exploring AngularJs has been a delightful experience for me, and I recently stumbled upon a fantastic plugin for Angular called angular-http-auth. This plugin allows you to seamlessly integrate an identification system. Does anyone know of a similar resou ...

Updating a Div on your webpage using a JQuery UI dialog: A step-by-step guide

I am currently trying to update my webpage from a JQuery UI dialog, but the code I have so far does not seem to be working. Any assistance or guidance would be greatly appreciated. function submit_new_site() { // These are the input text IDs on the ...

Access in-depth data by clicking on a map to get detailed information

Recently, I took on the challenge of managing a golf club website after the original creator had to step away. One urgent issue I need to address is fixing a malfunctioning flash animation that provides information about each hole on the course. My plan is ...

Ways to manage your javascript variables

Here is the code snippet I am working with: var json = jQuery.parseJSON(data); console.log(json) When I run this code, the output looks like this: Object {sql: "SELECT venta.cliente_tipodoc,count(*) AS cantidad FROM venta venta", results: Array[1], ...

Is it permissible for me to incorporate a package from the dependencies listed in the package-lock.json file into my

I'm looking to incorporate date-fns into my project. I currently have react-datepicker, which also uses date-fns. Can I simply utilize date-fns from react-datepicker, or do I need to install it separately in my project? ...

StyledTab element unable to receive To or component attributes

Is there a way to use tabs as links within a styled tab component? I've tried using the Tab component syntax with links, but it doesn't seem to work in this scenario: <Tab value="..." component={Link} to="/"> If I have ...

Setting up dynamic routing in AngularJS for links

I am facing some confusion regarding routing in AngularJS. Normally, we can configure routes in angular.config() when the angular module is loaded. At that time, we define static information such as routePath, templateUrl, and controller. However, I am u ...

Optimizing performance: Making the most of mongoose updateMany middleware

PROBLEM SOLVED: SOLUTION PROVIDED BELOW I have a piece of code where I am updating elements one by one: //registerCustomers.js const CustomerRegistrationCode = require("../models/CustomerRegistrationCode"); const setRegCodesToUsed = async (regC ...

React state object iteration doesn't produce any visible output

Trying to dynamically showcase checkboxes with starting values from the state using Material-UI for UI components. tagState: { All: true, Pizza: false, Breakfast: false, Chicken: false } Utilized Object entries and forEach to generate checkbox ...

including a code snippet within a dropdown menu or embedding it in a clickable button

Hey there, my name is Wouter Sanders and I am currently learning to code! I recently finished creating a RAL color picker for a project I'm working on. The only issue I've run into is trying to embed the code in a menu or button so that it doesn ...

What is the best way to implement rate limiting for asynchronous API calls within a specific timeframe?

I have a project that requires me to make over 500 calls simultaneously from my NodeJS server to a third-party server. The issue is that the third-party server has a restriction of only allowing a maximum of 50 calls per second. Can someone assist me in im ...

JavaScript's POST method is failing to fetch data from the API, yet it is able to retrieve data successfully in

I am experiencing issues when trying to retrieve data from an API using JavaScript. The API works fine in Postman, but it is not functioning properly in JavaScript. When I run the code, the console displays an error message stating "Failed to fetch respon ...

implement a click event handler for GLmol (webGL)

Check out GLmol, a Molecular Viewer built on WebGL and Javascript by visiting You can see a demo of GLmol in action at I am interested in adding a click function to GLmol. For example, when I click on a ball, I would like to retrieve information about it ...