Using TypeScript to create a list of key-value pairs, which will be converted into a list of objects

Is there a more elegant way to transform an array of key-value pairs into a list of objects in TypeScript?

let keys : string [] = ["name", "addr", "age"];
let values : string [][] = [["sam", "NY", "30"],["chris", "WY", "22"],["sue", "TX", "55"]];

The desired output:

[{"name": "sam", "addr": "NY", "age": "30"},
 {"name": "chris", "addr": "WY", "age": "22"},
 {"name": "sue", "addr": "TX", "age": "55"}]

Answer №1

Array.map function can be used to obtain the desired outcome.

let categories = ["name", "address", "age"];
let data = [["John", "123 Street", "25"], ["Jane", "456 Avenue", "30"], ["Tom", "789 Road", "40"]];

const result = data.map((item) => {
   let newData = {};
   item.forEach((value, index)=> {
      newData[categories[index]] = value;
   });
   return newData;
});

console.log(result);

Answer №2

Combine each array from vals with the elements in heads, then generate an object using Object.fromEntries:

let heads = ["name", "addr", "age"];
let vals = [["sam", "NY", "30"],["chris", "WY", "22"],["sue", "TX", "55"]];

const result = vals.map(val => Object.fromEntries(heads.map((head, idx) => [head, val[idx]])));
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

Having trouble getting angular and php to upload images?

I'm having trouble uploading images using Angular and PHP with the following code. Can someone please assist me? I'm getting an undefined index error on line 2 from the PHP side. const formData = new FormData(); formData.append('date', ...

Can you explain the concept of an anonymous block in JavaScript ES6 to me?

Recently, I came across an article on pragmatists which discussed some interesting ES6 features. However, one concept that caught my attention was the use of an anonymous block within a function. function f() { var x = 1 let y = 2 const z = 3 { ...

Upon a successful onChange event, the selected value reverts back to its default state

In my current project, I am creating a form where users can dynamically add or remove dropdowns to manage participants or voters. The goal is to prevent the same user from appearing in multiple dropdown lists once they have been selected. To achieve this ...

There seems to be a hitch in the functioning of the JavaScript codes

I'm having trouble calculating the amount using jQuery. Could someone please review my code and let me know what's wrong? Here are my Javascript and jQuery codes: After making changes: $(document).ready(function() { $('.home_banner&ap ...

The parameter in the Typescript function is not compatible with the generic type

What causes func1 to behave as expected while func2 results in an error? type AnyObj = Record<string, any>; type Data = { a: number; b: string }; type DataFunction = (arg: AnyObj) => any; const func1: DataFunction = () => {}; const arg1: Data ...

AngularJS can monitor input changes even when they are altered by JQuery

Having an input field with a text box and button, I am facing an issue where the library is unable to detect changes in the text input when I select a date and time using the button. I have attempted to use AngularJS and JQuery to monitor changes in this f ...

Buttons for toggling D3 bubble chart display mode

As a beginner in D3.js, I am exploring the creation of a bubble chart with a toggle button to switch between different presidential campaign candidates. While I succeeded in making the chart for one candidate, I am encountering difficulties implementing th ...

Having trouble retrieving coordinates from AJAX request to Google Maps API?

I am currently developing a weather application and one of the initial steps is to retrieve the longitude and latitude coordinates for a specific city based on its name. To achieve this, I am utilizing Google Maps API to gather the necessary information. ...

Simple steps to make an Angular Material mat-card expand to full screen

Currently, my goal is to create a portal-style page layout using Angular Material. This layout will feature a grid of cards where each card can be expanded to take up the majority of the visible page, covering all other cards that are not in focus. The car ...

"Modify the color of a div element by changing it from the color name to the hexadecimal

Is there a way to use color codes instead of typical color names, like #e06666 for red? content.push('<p><div class="color red"></div>Whole Foods Market</p>'); Any suggestions on how to achieve this? ...

Is there a way to display an animation when a page loads using jQuery that only plays for index.php and not other_page.php?

How can I trigger an animation on page load, specifically for my index.php page and not all other pages on my website? Is there a jQuery function that targets only the index.php page like this: $('index.php').ready(function()); If not, what i ...

Saving the current state of a member variable within an Angular 2 class

export class RSDLeadsComponent implements OnInit{ templateModel:RSDLeads = { "excludedRealStateDomains": [{"domain":""}], "leadAllocationConfigNotEditables": [{"attributeName":""}] }; oldResponse:any; constructor(private la ...

How can you eliminate the prop that is injected by a Higher Order Component (HOC) from the interface of the component it produces

In my attempt to create a Higher Order Component, I am working on injecting a function from the current context into a prop in the wrapped component while still maintaining the interfaces of Props. Here is how I wrap it: interface Props extends AsyncReque ...

When the form field is double-clicked, it automatically populates with information, but unfortunately it does not meet the

Presented below is a formgroup configuration: this.order = new FormGroup({ City: new FormControl('', Validators.required), Street: new FormControl('', Validators.required), DateOfDelivery: new FormControl('', Vali ...

Creating typescript as an optional feature for your ionic 2 applications

When incorporating a new JS library into an Angular component of an ionic 2 application, the initial step involves installing types through typings. I had the understanding that typescript was not a requirement for ionic 2. Is there a way to configure Io ...

When I execute the command `npm run start`, why does Tailwind not function properly while it works perfectly fine when I use `ng serve

I am working on an Angular 15 application that incorporates Tailwind CSS. Here is my Proxy.conf.json file: { "/api/": { "target": "http://localhost:8080", "secure": false, "changeOrigin&qu ...

Initiate a Gravity Forms form refresh after modifying a hidden field with jQuery

TO SUM IT UP: Is there a way in Javascript to activate an update on a Gravity Form that triggers the execution of conditional logic? ORIGINAL QUESTION: I'm using Gravity Forms and I have set up an "on change" event $('#gform_1').find(&apos ...

A guide on managing multiple onClick events within a single React component

Including two custom popups with OK and Cancel buttons. Upon clicking the OK button, a review is composed. This review code is then sent to the server via a post request. Subsequently, the confirmation button reappears along with a popup notifying the user ...

Using jQuery to toggle an open and close button

My icon functions as an open/close button. When opened, it turns red and rotates 45 degrees. The issue arises when trying to close it. Changing the div class causes the icon to disappear while in its active state. Below is the jQuery code I am using: $(". ...

Did Jscript.net already offer many of the same features as TypeScript?

I find myself lacking knowledge about TypeScript. After reading through introductory articles, I fail to see any groundbreaking innovations that justify the widespread praise it has received. [1] In terms of syntax, didn't JScript.net already provide ...