Generate an array of objects using the values from a different array of objects

I have an array of objects:

const users = [
  { name: 'Alice' },
  { name: 'Eve' }
]

However, I want to transform it into an array like this:

const updatedUsers = [
  { key: 'Alice', value: 'Alice', text: 'Alice' },
  { key: 'Eve', value: 'Eve', text: 'Eve' }
]

Currently, I am achieving this using the following method:

const updatedUsers = []
users && users.length > 0 && users.map(user => {
  updatedUsers.push({ key: user.name, value: user.name, text: user.name })
})

Is there a simpler way to achieve this transformation without manually building each object and pushing it into a new array?

Answer №1

To efficiently create the array in one go, you can utilize the .map function along with Object.fromEntries on an array of entries:

const user = [
  { name: 'Bob' },
  { name: 'Frank' }
];
const result = user.map(({ name }) => Object.fromEntries(
  ['key', 'value', 'text'].map(key => [key, name])
));
console.log(result);

In case user is possibly undefined, you can substitute it with an empty array initially:

const result = (user || []).map(...

Checking for user.length beforehand is unnecessary. If the length is 0, the result will still be the empty array since there are no items to iterate over.

Answer №2

When utilizing the .map() method, it is important to always return the new element within the callback function. Failure to do so indicates that you should consider using .forEach() instead.

Additionally, you have the option to use destructuring in order to prevent redundancy when referencing u.name.

result = user ? user.map(({name}) => ({ key: name, value: name, text: name })) : [];

Answer №3

If you want to add new fields to your object, consider using the following syntax:

result["key"] = u.name

Answer №4

Consider utilizing the map() function by @barmar or the reduce() function below:

const result = user.reduce((res, u) => {
    res.push({ key: u.name, value: u.name, text: u.name }); return res
}, [])

Explore the Benefits of JavaScript's Reduce Method

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

The appearance of the logout button may differ depending on the web browser being used

I have implemented a straightforward logout button using the following code: <li><a href="http://localhost:8666/web1/profile/mainpage/logout.php" onclick="return confirm('Are you sure to logout?');">Log Out</a>&l ...

Utilize toggle functionality for page rotation with rxjs in Angular framework

Managing a project that involves a container holding multiple cards across different pages can be overwhelming. To address this, the screen automatically rotates to the next page after a set time interval or when the user presses the space bar. To enhance ...

Exploring the Power of D3.js: Loading and Visualizing Multiple Networks using JSON Files and the Force

I have a collection of networks consisting of nodes and links stored in various JSON files. I am using D3.js to load them into a Force Layout, where they each load and layout perfectly when loaded individually. However, I would like to enhance the function ...

Transforming properties of objects to and from pointers when passing them as arguments in functions

In my C function, I am dealing with objects of the node type that have two attributes: a pointer to a key object and an integer data. The method signature key_comp(key, key) requires two keys as arguments, but the node object contains a pointer to a key. ...

The alignment issue persists in HTML/CSS despite troubleshooting efforts

I am facing a challenge while attempting to center text within a modal window, despite my efforts the text remains uncentered. This is my HTML code: <div ng-init="modalCompassDir()"> <div class="myModal"> <img class='floor ...

Changing an element in an array by using a specific input

With the usage of either JavaScript or Jquery, I possess an array that has been arranged in accordance with Start Date (coordinates): [{ elem: '<div id="task7">', startDate: 864, endDate: 999, order: 0 }, { elem: '<div id ...

Connecting with Node JS, utilising the power of Socket.IO, Express, and establishing

Hey everyone, I have an interesting concept that I'd like to discuss with you to get your thoughts on its feasibility. The idea is to set up an RFID reader connected to a MacMini (with the Mini hidden and only the RFID visible). An iPad would also be ...

What is the process for modifying the headers of a post request in Express when

I have a Node/Express application and I'm looking to incorporate an image upload feature into an order form. While I can successfully use the action link in the HTML form to perform a POST request, I also want my JavaScript file associated with this ...

Steps for extracting a date from a JSON object

My JSON object includes a field for birthdate: JSONObject obj = new JSONObject(response); User user = new User(); user.setuserID(obj.getString("userID")); user.setisMale(obj.getBoolean("isMale")); user.setEmail(obj.getString("email")); // user.setBirthdat ...

Discovering every array element within a database

After building an array like this arr = ["1","2"] I am interested in checking if these IDs exist in the MongoDB user collection. Can someone guide me on how to write a Mongoose query for this task? user.find({'empid':'arr'},(err,res)) ...

Connect the front end files, including HTML, CSS, and JavaScript, to the Node.js backend

I'm a beginner in web development and recently completed an online course on node.js and express. However, the course didn't cover how to add HTML, CSS, and JS files when using Node. I attempted the following: var express = require('expres ...

Set a maximum limit for the number of checkboxes that can be selected

If there are 10 checkboxes on a page, I am searching for a specific behavior: Use a variable called maxSelections to control the maximum number of selectable checkboxes Once maxSelections is reached, disable the other checkboxes on the page Even after re ...

Creating a paginated table with Nextjs, Prisma, and SWR: A step-by-step guide

I am attempting to set up a paginated table utilizing Nextjs, Prisma, and SWR. The table will display a list of invoices sorted by their ID. Here is an example of what it would look like: https://i.sstatic.net/WymoH.png To fetch all the data to the api r ...

A guide to crafting a fresh WordPress post with the help of the wpapi library for Node.js

After attempting to use the wpapi module to generate a post in WordPress, I encountered a puzzling issue. Despite receiving a 200 Success response, the request body was empty and no post was actually created. var wp = new WPAPI({ endpoint: 'http:/ ...

Guide for Extracting a String in JavaScript that Includes Numerals for Color Code Alteration, Resulting in Formats like 32m+ or 31m-

Attempting to create a Firebase cloud function in JavaScript that sends email notifications for any changes in the Firebase remote config. Upon each remote config change, the string received is in the following format: { parameters: { [32m+ newer_value: ...

Interoperable Generic Objects in C++ Files (Using Boost Filesystem and Libconfini)

Here's a tricky one for you all. I'm working on creating a program that uses an INI config file (utilizing the libconfini C library), which has the following structure: [General] output_directory = /scratch/miles/trans_assembly_pipeline/ [SRA a ...

Ways to guarantee that the factory promise is fulfilled prior to the execution of the

So far, I have always found valuable help by studying existing answers on stackoverflow, but now I've hit a roadblock. I'm currently working on an app that utilizes a directive to generate calendar month boxes. <app2directive class="column_5 ...

Seeking assistance in comprehending the method for styling table data using inline CSS in a JavaScript file

I am currently using a JavaScript file that was created for me to update form data based on user selections and display radio buttons along with the corresponding costs. Although the inline CSS in this script works perfectly fine in Chrome and Firefox, it ...

Verify the presence of a JSON object within the session storage using JavaScript

I'm currently developing a website where some data is stored within the session. In the initial page, I need to verify if the JSON object already exists in the session. Below is the code snippet that's causing issues: var passedTotal = JSON.par ...

Troubleshooting problem with jwPlayer resizing in Firefox and Opera browsers

<script type="text/javascript" src="js/jwplayer/jwplayer.js"></script> <div id="myElement"">Loading the player...</div> <script type="text/javascript"> jwplayer("myElement").setup({ file: "video/mosk.mp4", ...