What is a sleek method for including a key and value pair to an object using an array?

In a project using angular2/typescript, I am working with an array of objects that contain key/value pairs from a database. These values are then displayed in a table on the UI using ag-grid-ng2.

The table headers are dynamic and set in the database.

One task I have is to convert an array of key/values into a single object format like this:

const things = [
  {
    field: 'some_table_header', 
    humanReadable: 'Some table header'
  }
];

This needs to be transformed into:

const anObjectFullOfThings = {
  some_table_header: 'Some table header'
};

I believe there may be a more elegant and concise way to achieve this, rather than using the current method:

let anObjectFullOfThings = {};

things.forEach((thing) => {
  anObjectFullOfThings[thing.field] = thing.humanReadable;
});

I wonder if there is an alternative approach to mapping an array to object keys?

Answer №1

Your current implementation is adequate.

Some individuals may opt to utilize the reduce method:

const objectFromThings = things.reduce((accumulator, currentValue) => {
    accumulator[currentValue.field] = currentValue.humanReadable;
    return accumulator;
}, {});

...however, some might argue that using reduce in this scenario is purely subjective, especially since it doesn't actually reduce anything, but rather maintains the same object structure throughout the loop.

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

Uploading images simultaneously while filling out a form

Currently, I have a form that requires users to fill it out and upload an image. However, there is a delay of up to 30 seconds when the user hits "Submit" due to the image size being uploaded. I'm interested in finding a way to initiate the image upl ...

Issue: The variable does not appear to be getting updated

After spending the last 2 hours analyzing this JS code, I am still unable to figure out why the variable "message" is not being changed to "User already exists." The bizarre thing is that the code block labeled "Inside first if" is executed, but the "mes ...

Code error TS2345 occurs when assigning the argument of type '{ headers: HttpHeaders; }' to a parameter of type 'RequestOptionsArgs'. This indicates a mismatch in the type of data being passed, causing an

Upon running ionic serve, these are the results that I am encountering. My setup consists of Ionic4 version with Angular 8. While executing the command, this error appears: src/app/home/home.page.ts:60:77 - error TS2345: Argument of type '{ headers ...

The error "navigator.permissions.query is not a defined object" is encountered in the evaluation

Whenever I try to access my website on an iPhone 7, I encounter a frustrating error. The main screen loads without any issues, but as soon as I click on something, a white bank screen appears. I believe this piece of code might be the cause: useEffect( ...

Trigger a click event on a div element that is nested within a form

Having trouble displaying an alert when clicking on a disabled button because the user needs to first click on a terms checkbox. Here's my jQuery code: $('#divButton').on("click", function() { if ($('#buybutton').prop('d ...

What are the consequences of relying too heavily on deep type inference in React and Typescript?

In the process of migrating my React + Javascript project to Typescript, I am faced with preserving a nice unidirectional flow in my existing code. The current flow is structured as follows: 1. Component: FoobarListComponent -> useQueryFetchFoobars() 2 ...

If there is a lack of text at the beginning, then insert the

I am currently trying to figure out a solution to automatically add our domain name if it is not included when entering the username. In the code snippet below for my form, I want the script to check if "domainname\" is present before the username. I ...

When the typeof x is determined to be "string", it does not result in narrowing down to just a string, but rather to T & string

Could someone help me understand why type narrowing does not occur in this specific case, and return typing does not work without using: as NameOrId<T>; Is there a more efficient way to rewrite the given example? Here is the example for reference: ...

What's the best way to invoke a function from a different JS file or create a custom event in JQuery that includes a parameter as a data object?

I am facing an issue while using requireJS to call a function from a required JS file. In my main app.js "controller", I have included (plugin)app.js, which contains all plugin configurations and related functions. The snippet below is from app.js defin ...

The process of extracting all arrays from a JSON object

Within my JSON object, there is a list of countries each with multiple regions stored in an array. My goal is to extract and combine all the regions into one single list. However, when I attempt to map the data, it does not consolidate all the regions as e ...

When you hover over HTML tables, they dynamically rearrange or shift positions

Issue: I am encountering a problem with multiple tables where, upon hovering over a row, the tables are floating rather than remaining fixed in place. Additionally, when hovering over rows in the first or second table, the other tables start rendering unex ...

The error "TypeError: ollama.chat is not a function" has occurred when trying to use the ollama module in

Currently, I am grappling with a Node.js project that requires me to utilize the ollama module (ollama-js). The problem arises when I invoke the async function chatWithLlama() which contains ollama.chat(), resulting in the following error being thrown: Ty ...

In JavaScript, generate a new column when the text exceeds the height of a div

Is it possible to create a multicolumn layout in HTML that flows from left to right, rather than top to bottom? I am looking to define the height and width of each text column div, so that when the text overflows the box, a new column is automatically ge ...

I'm looking for a sample of RadPieChart for nativescript + angular. Can anyone help me out?

I'm currently working on a multi-platform application that requires a PieChart to be displayed on the main screen. Can someone point me to a comprehensive example of how to implement this? I have tried following this guide and modifying it according ...

Trigger video to play or pause with every click event

Looking to dynamically change the HTML5 video tag with each click of an li tag. Here is the current structure: <div class="flexslider"> <ul class="slides"> <li> <video> <source type="video/mp4" src="http://t ...

Problem with Raphael Sketch and Request to Ajax

Utilizing Raphael.js and jQuery Ajax, I am attempting to display some dots (circles) on the map in this [Demo][1]. I have a PHP file called econo.php which looks like this: <?PHP include 'conconfig.php'; $con = new mysqli(DB_HOST,DB_USER,DB_P ...

Guide to adding a file upload progress bar to your website

Is there a way to enhance file upload experience on my web application beyond the usual animated gif? I'm currently using .Net, but open to platform agnostic solutions as well. ...

JavaScript HTTP Requests

I came across this AJAX example in Stoyan Stefanov's book Object Oriented JavaScript on page 275. The example involves requesting three different files. I have a few questions that I was hoping someone could help me with! What does the line xhr.se ...

Why is it that GetElements does not provide immediate results upon execution?

Just diving into the world of Javascript for the first time and experimenting with it on Chrome, but running into unexpected results. When I try: document.getElementsByTagName("h1") I anticipate seeing: <h1>tester h1 in body</h1> Instead, wh ...

Attempting to transmit unique symbols using JQuery Ajax to a PHP script

I am using JQuery Ajax to send special characters to a PHP file. sending_special_characters.js var special_chars = '!@#$%^&*()_+-='; var dataToSend = 'data=' + special_chars; $.ajax({ type: "POST", ...