Ways to transform an Array into an object

I had the idea to create a personalized dictionary for customers by utilizing the reduce function. Currently, I am achieving this using the forEach method.

const customers = 
  [ { name: 'ZOHAIB', phoneNumber: '0300xxxxx', other: 'anything'     } 
  , { name: 'Zain',   phoneNumber: '0321xxxxx', other: 'other things' } 
  ] 

let customersDictionary = {};
customers.forEach(customer => {
  customersDictionary = {
      ...customersDictionary,
      [ customer.phoneNumber ]: {name: customer.name},
      };

However, my goal is to obtain the same result but with the reduce method.

customersDictionary = 
  { "0300xxxxx": {"name": "ZOHAIB"}
  , "0321xxxxx": {"name": "Zain"}
}

Answer №1

This code snippet is expected to provide the desired outcome.

let userList = [
  { username: "JohnDoe", email: "johndoe@example.com", role: "admin" },
  { username: "JaneSmith", email: "janesmith@example.com", role: "user" },
];

let userDictionary = userList.reduce(
  (acc, { email, username }) => ({
    ...acc,
    [email]: { username },
  }),
  {}
);

Answer №2

Forget about reduce. You can achieve the same result in just one line using a combination of Array.prototype.map and Object.fromEntries:

Object.fromEntries(customers.map(c => [c.phoneNumber, { name: c.name }]));

Alternatively, you could also use reduce like this:

customers.reduce((acc, c) => {
  acc[c.phoneNumber] = { name: c.name };
  return acc;
}, {});

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

Numerous jQuery pop-up windows are being generated instead of just one as intended

When I load an editing form asynchronously on my web page using jQuery.get and display it within a jQuery dialog, multiple instances of the div that I apply .dialog to are unexpectedly being appended to document.body. Here is the code snippet for loading: ...

How can I extract the value of a JavaScript variable using jsoup in an HTML document?

<html> <script type="text/javascript"> var map = null; jQuery(function($) { L.marker([50.065407, 19.945104], {title: 'Cat'}) .bindPopup('<h3>Cat</h3> ...

Non-responsive Click Event on Dynamically Created Div Class

I am facing some uncertainty in approaching this problem. In the HTML, I have created buttons with additional data attributes. These buttons are assigned a class name of roleBtn. When clicked, they trigger the jQuery function called roleBtnClicked, which ...

Ensure that the <TabPanel> content occupies the entire width and height of its parent container

Currently, I am working with React and material-ui. Specifically, I am utilizing an appbar with tabs and my goal is to have the content of each tab expand to full width and height when selected. If you'd like to see an example, check out this sandbox ...

Unlocking the Potential: Employing postMessage in an iFrame to Seamlessly Navigate Users towards an Enriching Destination on

One of my webpages includes an iframe. Here's the challenge: I want a button within the frame to redirect users to another page without reloading the iframe's content. Instead, I want the URL of the main window to change. Unfortunately, I haven& ...

Resolving the issue: "How to fix the error "Credentials are not supported if the CORS header 'Access-Control-Allow-Origin' is '*' in React?"

Recently, I encountered some CORS issues while using a third party API in my front-end application. After reaching out to the API maintainers, they lifted the CORS control by adding a * to Access-Control-Allow-Origin, which seemed like the perfect solution ...

Introduce a timeout in the ajax request

I'm currently facing an issue with adding a 2-second delay between the loader icon and the success message displaying the data as html. I attempted to use setTimeout in my ajax code with a specified delay number, but it doesn't seem to be workin ...

Automatically identify the appropriate data type using a type hint mechanism

Can data be interpreted differently based on a 'type-field'? I am currently loading data from the same file with known type definitions. The current approach displays all fields, but I would like to automatically determine which type is applicab ...

Is there a way to remove <font> tags using Javascript designMode?

Currently, I am in the process of developing a WYSIWYG editor as a hobby project. My approach involves utilizing an iframe with design mode enabled and leveraging the execcommand feature in JavaScript to implement the editor functionalities. For instance, ...

Could you display the picture prior to the function commencing?

This is the image that needs to be loaded before the loop begins. <div id="attendenceGridDivLoader" style="display:none"> <img src="<?php echo base_url() . 'images/loader.gif'; ?>" /> </div> <select onchange=checkAll ...

React-redux: Data of the user is not being stored in redux post-login

Hello everyone, I am fairly new to using react-redux and I'm currently facing an issue with storing user information in the redux store after a user logs in. I am utilizing a django backend for this purpose. When I console out the user in app.js, it ...

What is the best way to display a Vuex state based on a function being activated?

I have noticed similar questions on this topic but couldn't find a solution, so I decided to create my own. Here's the issue: I have an array named "allCountries" in the state, initially filled with 250 country objects. I am successfully render ...

Tips for utilizing javascript document.createElement, document.body, and $(document) in an HTML web resource for Microsoft CRM code reviews

Let me start off by saying that I am not a regular blogger and I am feeling quite confused. If my question is unclear, please provide guidance for improvement. I recently submitted a Microsoft CRM PlugIn to the Microsoft Code Review. I am new to Javascrip ...

The color of the progress bar in JS is not displaying properly

My work involves using jQuery to manipulate progress bars. The issue I am facing is defining standard colors that should be displayed on the progress bar based on the value received. Here is my code: var defaultSegmentColors = ['#FF6363', &ap ...

Tips for extracting valuable insights from console.log()

I'm currently utilizing OpenLayers and jQuery to map out a GeoJson file containing various features and their properties. My objective is to extract the list of properties associated with a specific feature called "my_feature". In an attempt to achi ...

Combine angular ui router templates using grunt into a single file

Currently, I am working on an angular-ui-router project that consists of 150 files scattered all over. My goal is to create a grunt task that will merge all these files into a single index.html file structured like this: <script type="text/ng-template" ...

Encountering difficulties in transferring bulky files with the request module in Node.js

When working on a Node.js project, I encountered an issue with transferring files from the computer to the server. While I am able to successfully send files that are up to 2mb in size, larger files fail to upload. Here is the code snippet I am using: var ...

Uh-oh, Ajax encountered a 500 Internal Server Error!

Utilizing ajax to fetch events from my database has hit a snag. Instead of displaying the results, there is nothing visible on the screen, and the console is showing this error message: POST http://www.example.com/system/live_filter.php 500 (Internal Se ...

Facilitating the integration of both Typescript and JavaScript within a Node application

We are currently integrating Typescript into an existing node project written in JS to facilitate ongoing refactoring efforts. To enable Typescript, I have included a tsConfig with the following configuration: { "compilerOptions": { "target": "es6", ...

What is the proper way to utilize document.getElementById() within a standalone js file?

As I dive into learning web development for the first time, I've decided to keep my scripts organized in separate files. However, I'm facing a challenge when trying to access elements from these external files. Below is a snippet of the JavaScri ...