Adding properties with strings as identifiers to classes in TypeScript: A step-by-step guide

I am working with a list of string values that represent the identifiers of fields I need to add to a class.

For instance:

Consider the following string array:

let stringArr = ['player1score', 'player2score', 'player3score'];

After some transformation code, I aim for the output to be:

{player1score: 100, player2score: 100, player3score: 100}

How can I achieve this?

let row = {};
stringArr.forEach(player => {
    // What steps should I take here?
    // something like row.addProp(player, score)?
});

Note:

This conversion is necessary as I plan to visualize the data using v-charts, and the rows data must be structured like this:

let rows = [
    {time: ..., player1score: ..., player2score: ..., player3score: ...},
    ...
];

Answer №1

To assign a specific value to each player in the string array, simply add a new key-value pair to the object

let row = {};
stringArr.forEach(player => {
    row[player] = 100;
});

Answer №2

To create the object using JavaScript's bracket notation, you can follow this example:

let keysArray = ['key1', 'key2', 'key3'];
let newObj = {};
keysArray.forEach(key => newObj[key] = 'value');
// newObj = {key1: 'value', key2: 'value', key3: 'value'}

For additional information, refer to MDN.

Answer №3

If you're using a modern browser, you have the option to utilize Object.fromEntries().

let stringArray = ['player1score', 'player2score', 'player3score'];

let object = Object.fromEntries(stringArray.map(value => [value, 100]))

console.log(object)

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

When Using TypeScript with Serverless, 'this' Becomes Undefined When Private Methods are Called from Public Methods

Currently, I am working on constructing an AWS Serverless function using TypeScript. My focus is on creating an abstract class with a single public method that invokes some private methods. Below is the simplified version of my TypeScript class: export ...

Encountering a problem while trying to execute npm run serve on a newly created Vue-CLI project

Struggling to execute npm run serve on a fresh vue Project made with the Vue CLI. I initiated the project using vue create app, navigated to the project directory cd app, and ran npm run serve, a routine I have followed in previous projects. However, start ...

Display the item request form whenever a selection of an unidentified item is made using select2

I want to implement select2 for a company search feature. In case the desired company is not available in the existing dataset, I need to provide an option for users to request adding the company data. This is the HTML code: <head> <link href=& ...

Leveraging a VueJS prop as a variable in an array mapping operation

Trying to figure out a solution where a variable (prop) can be used in an array map function. The initial code snippet looks like this: var result = this.$store.getters['example/store'].map(a => a.fixed_column) I aim for fixed_column to be ...

Move information from one webpage to a different page

After developing a site using NextJs, I successfully integrated Discord login functionality and was able to retrieve the user's guilds in the oauth file. Now, I am looking to send this list of guilds (in JSON format) to my dashboard page. In the oau ...

My code to hide the popup when clicking outside doesn't seem to be working. Can you help me figure out why?

After searching around on stackoverflow, I stumbled upon a solution that worked for me: jQuery(document).mouseup(function (e){ var container = jQuery(".quick-info"); if (container.has(e.target).length === 0) { container.hide(); } }); ...

Using perl ajax to modify a table

In my current Perl script, I am working on a functionality where I retrieve data from an xls file and display it as input text on a webpage. The objective is that when a user selects the edit option from a menu, the entire table fetched from the xls file w ...

How can I achieve this using JavaScript?

I am attempting to create a TypeScript script that will produce the following JavaScript output. This script is intended for a NodeJS server that operates with controllers imported during initialization. (Desired JavaScript output) How can I achieve this? ...

Creating a universal function to handle setTimeout and setInterval globally, inclusive of clearTimeout and clearInterval for all functions

Is it possible to create a universal setTimeout and setInterval function with corresponding clearTimeout and clearInterval for all functions while passing values to them? The situation is as follows: 1. More than 8 functions utilizing setInterval for act ...

How can I display input only when a checkbox is selected? React with Next.js

I'm trying to figure out how to handle this task, but I'm a bit confused on the approach. I would like to display the promo code field only when the checkbox (I have a promo code) is checked. Additionally, it would be ideal to reveal this field ...

Unable to find any matches when conducting a search through Google Apps Script

After spending days analyzing the code, I am encountering an error that states "uncaught reference error: google is not defined." This issue seems to occur specifically in line 360. Curiously, when inspecting the original code editor, line 360 simply conta ...

"Unlocking the Potential: Maximizing the Benefits of the top.gg Vote Web

My bot has been verified on top.gg, and I'm looking to offer rewards to users who vote for my bot. How can I detect when someone votes for my bot, get their ID, check if it's the weekend, and take action after the vote? Essentially, how do I util ...

Error in AWS Cloud Development Kit: Cannot access properties of undefined while trying to read 'Parameters'

I am currently utilizing aws cdk 2.132.1 to implement a basic Lambda application. Within my project, there is one stack named AllStack.ts which acts as the parent stack for all other stacks (DynamoDB, SNS, SQS, StepFunction, etc.), here is an overview: im ...

The function buf.writeBigUInt64BE is not recognized as a valid function and returns an undefined error

I'm attempting to implement the code below on my React Native iOS device: import { Buffer } from "buffer"; const buf = Buffer.alloc(8) buf.writeBigUInt64BE(BigInt(123), 0) const value = buf.readBigUInt64BE(0) console.log(value) However, I&a ...

Dealing with numerous promises simultaneously using AngularJS Factory

I have created a code that makes multiple $http calls recursively and saves all the promises it returns in an array. Then, I resolve all of them and save the responses in another array. Now, my question is: How can I efficiently return this final array to ...

JavaScript problem with hovering action causing additional buttons to appear

Currently, I am developing a user interface where, upon hovering over an LI element, 2 buttons appear to provide additional functionality - "edit" and "remove". However, I am facing challenges with the mouse hit zones. The mouseover function works effect ...

Is it possible to derive a TypeScript interface from a Mongoose schema without including the 'Document' type?

Using ts-mongoose allows me to define interfaces and schemas for my data in one place. I then export them as a mongoose schema along with the actual interface. The challenge I'm facing is finding a simple way to extract that interface without includi ...

Ordering dates by week in AngularJS 1

Currently, I have a list of objects: [{ name: one, date: 2017-09-18 }, { name: two, date: 2017-09-11 }, { name: three, date: 2017-09-13 }] I am looking to organize this list by week. Perhaps like the following structure: { 1week(or , m ...

Exploring Data within Data Structures

I am currently making two JSON requests in my code: d3.json("path/to/file1.json", function(error, json) { d3.json("path/to/file2.json", function(error, json2) { }); }); The structure of json 2 looks like this: [ { "city" : "LA", "locati ...

The div background image in Vue.js is displaying a 404 not found error

I've encountered an issue while trying to set a background for a div. Strangely, when using the same relative path with an img tag everything works fine, but as soon as I try to achieve the same result with a div, I receive a 404 error. This img tag ...