Incorporate changing keys and fluctuating values into a JavaScript object

I am trying to create a function in TypeScript that will return an object like this:

    marked = {
      '2024-08-21': {
        dots:[food, recycling]
      },
      '2024-08-22': {
        dots:[food, recycling]
      }
    }

Here is the code I have written so far.

function addKeysAndValuesDynamically(days: string[]): any {
  var marked = {};
  const food = {key: 'food', color: 'brown'};
  const recycling = {key: 'recycling', color: 'green'};
  days.forEach((day: string) => {
    marked[day]['dots'] = food, recycling;
  });
  return marked;
}

var days: string[] = ['2024-08-21', '2024-08-22'];
var marked = addKeysAndValuesDynamically(days);
console.log(`marked = ${marked}`);

However, when I run the code, I receive an error message:

TypeError: Cannot set property 'dots' of undefined
.

Answer №1

Are you new to TypeScript coming from JavaScript and looking to avoid using types? Here's a way to achieve that with interfaces:

interface KeyColor {
    key: string;
    color: string;
}

interface Marked {
    [day: string]: {
        dots: [KeyColor, KeyColor]
    }
}

function dynamicallyAddKeysAndValuesToDays(days: string[]): Marked {
  const marked: Marked = {};
  const food = {key: 'food', color: 'brown'};
  const recycling = {key: 'recycling', color: 'green'};
  days.forEach((day: string) => {
    marked[day] = { dots: [food, recycling] }
  });
  return marked;
}

var days: string[] = ['2024-08-21', '2024-08-22'];
var marked = dynamicallyAddKeysAndValuesToDays(days);
console.log(marked); // log object properties this way to view content

Check out the code on Playground

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

Tips for obtaining the accurate HTML code format using Angular 2's input feature:

I am looking to retrieve all the code with an input as [input] and a tag as #tag. When attempting to obtain HTML code with jQuery using console.log($("#content")[0].outerHTML);, this is an example of how the code looks: <div dnd-droppable [dropZones]= ...

Please provide TypeScript code for a React wrapper function that augments a component's props with two additional functions

During the course of my project, I implemented a function wrapping React component to incorporate undo/redo functionality using keyboard shortcuts Ctrl+Z and Shift+Ctrl+Z. Here is an example: import React from 'react'; interface WithUndoRedoProp ...

how can I retrieve an array of nested objects from two interrelated tables that have a one-to-many relationship using

Hey everyone, I have a scenario where I'm working with 2 MySQL tables: itemsClass which holds various classes, and itemType which links to itemClass and contains type values for a specific class. My goal is to create a service that returns an Observa ...

How can I enable editing for specific cells in Angular ag-grid?

How can I make certain cells in a column editable in angular ag-grid? I have a grid with a column named "status" which is a dropdown field and should only be editable for specific initial values. The dropdown options for the Status column are A, B, C. When ...

GUIDE: Creating an Angular library comprised of standalone feature sub-libraries

Currently in the process of developing a custom Angular library using Angular v 8.1.0, I am interested in figuring out how to organize it into different sub-libraries. For instance, the Angular core is divided into separate parts like: @angular/common @ ...

"In the combined declaration of 'DepartmentListComponent', all individual declarations must either be exported or kept local." - error message regarding routing components in TypeScript file

I followed a video tutorial to write this code, but it's not working as expected and is throwing some errors. Is it possible that the tutorial is outdated and using an older methodology? The code seems to be hard-coded without using any services. Her ...

The name 'console' could not be located

I am currently working with Angular2-Meteor and TypeScript within the Meteor framework version 1.3.2.4. When I utilize console.log('test'); on the server side, it functions as expected. However, I encountered a warning in my terminal: Cannot ...

Defining a TypeScript conditional return type that may include undefined

Here is the function I currently have, but unfortunately I encountered the following error: Type '(T & undefined) | { obj: T & ({} | null); }' is not assignable to type 'T extends undefined ? undefined : { obj: T; }'. Type & ...

Vercel deployment encountered an AxiosError with a status code of 404

I am currently working on an API route called app/api/posts/route.ts, which is responsible for fetching all posts from my database using Prisma ORM. In the localhost environment, the database is hosted on my local PostgreSQL server. However, in production, ...

Tips on dividing an Axios request into multiple files in ReactJS?

I've been working on a project that involves making Axios calls in multiple files, and I'm looking to modularize it by passing the call as a prop to other files that require it. Below is the componentDidMount() method containing the call: comp ...

NestJS WebSocketGateway fails to initialize due to a technical glitch

After following the instructions in the NestJS documentation, I set up the websockets gateway within the AppModule. The server is starting without any issues, and I'm able to serve static assets via HTTP successfully. However, I'm facing difficul ...

What is the proper way to define a generic object interface in Typescript?

Within my code, I have constructs that resemble the following: { classNames: { foo: 'foo', .... bar: 'bar' }, method1: () => {....}, method2: () => {....}, stringKey1: 'stringKey1', ... stringK ...

The functionality of provideRouter and RouterConfig cannot be located in the updated @angular/router version 3.0.0-alpha.3^

Currently in the process of migrating an angular2 app to RC2 and experimenting with the router's version 3 alpha. Followed the setup provided by the angular docs for routing as demonstrated in the plunker. However, encountering the following errors: ...

Guide on bringing in Javascript file into your Ionic/Angular application

Within my Ionic 2 application, I have incorporated three.js along with a PLYLoader extension for three.js (accessible here: https://github.com/mrdoob/three.js/blob/master/examples/js/loaders/PLYLoader.js) Integrating three.js is straightforward by includi ...

Exploring the inner components of an entity without the need for external tools

I am currently enhancing TypeScript usage in a project by implementing generics. The challenge I am facing involves dealing with a complex object retrieved from the backend, which consists of a class with numerous attributes, most of which are classes them ...

What is the best way to access individual items within an *ngFor loop in Angular?

Is it possible to retrieve the value of item.profile image and utilize it in the update function shown in the code below? <ion-content> <ion-grid style ="text-align: center"> <ion-row class="ion-align-items-center" > ...

Encountered an eas error during Android build process

When I try to execute the command "eas build --platform android" I encounter the following error message: "✖ Build failed ...

Defining optional parameters in TypeScript

Currently, I am working on implementing strong typing for a flux framework (specifically Vuex). Here is my current code: const actions = { first(context: Context, payload: string) { return doSomething(context, payload); }, second(context: Context) { r ...

Creating a unique Angular 2 Custom Pipe tutorial

I've come across various instances of NG2 pipes online and decided to create one myself recently: @Pipe({name: 'planDatePipe'}) export class PlanDatePipe implements PipeTransform { transform(value: string): string { return sessionStor ...

Tips for sending data returned asynchronously from an Observable in Angular from a Child component to its Parent

I am facing a challenge passing Async data from child to parent component. When I try to access console.log(this.values) within the ngAfterViewInit() method in the parent component's HTML page load, it returns an empty value. However, upon clicking th ...