What is the best way to extract a specific property from an object?

Consider the following function:

getNewColor(): {} {
    return colors.red;
}

Along with this object:

colors: any = {
  red: {primary: '#ad2121',secondary: '#FAE3E3'},
  blue: {primary: '#1e90ff',secondary: '#D1E8FF'},
  yellow: {primary: '#e3bc08',secondary: '#FDF1BA'}
};

Whenever getNewColor() is called, it should return a new color object from the collection (not repeating any previously returned colors).

If we were to run:

console.log(getNewColor());
console.log(getNewColor());
console.log(getNewColor());

The expected output would be:

{primary: '#ad2121',secondary: '#FAE3E3'}
{primary: '#e3bc08',secondary: '#FDF1BA'}
{primary: '#1e90ff',secondary: '#D1E8FF'}

What is the most effective approach to implement the functionality of getNewColor()?

Answer №1

Behold, behold, behold! Your mystical solution awaits:

elements = {
  fire: {symbol: '🔥',color: 'red'},
  water: {symbol: '💧',color: 'blue'},
  earth: {symbol: '🌿',color: 'green'}
};

const getElement=()=>{
    const keys = Object.keys(elements);
    const key = Math.floor(Math.random() * keys.length);
    return elements[keys[key]]
}

However, it is quite evident that your query could benefit from a dash of effort

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 encapsulating a promise while maintaining the original return type

In my code, there is a function that utilizes an axios instance and is of type async function register(data: RegisterData): Promise<AxiosResponse<UserResponse, any>> export const register = (data: RegisterData) => api.post<UserResponse> ...

Troubleshooting: Angular 6 issue - Unable to toggle visibility using ngIf

I am currently learning Angular and I'm working on the app.component.html as shown below: <app-login *ngIf="!loggedIn"></app-login> <section *ngIf="loggedIn" style="background:#EBF0F5;"> <div class="container"> ...

Steps for launching a stackblitz project

Apologies for the novice question. As a beginner in Angular (and StackBlitz), I have created a StackBlitz project to seek assistance on an Angular topic (reactive forms). However, I am unable to run it. Can anyone guide me on how to do so? Thank you. ...

Mocking a promise rejection in Jest to ensure that the calling function properly handles rejections

How can I effectively test the get function in Jest, specifically by mocking Promise rejection in localForage.getItem to test the catch block? async get<T>(key: string): Promise<T | null> { if (!key) { return Promise.reject(new Error(&apo ...

Selecting a GoJS Node using keys

In Angular with TypeScript, what is the best way to select a node from a diagram based on its key? Currently, I am required to left-click a newly created node in order to select it, but I would like for it to be automatically selected upon creation. I ha ...

Exploring the world of AWS Amplify Cognito in Angular through thorough unit

Just started diving into unit testing and decided to tackle adding test coverage for my current app. Struggling with writing the unit test cases for a specific service within an AWS file. import { Injectable } from '@angular/core'; import { Behav ...

Is there a way to transform a Map<Integer, Object> into JSON using GSON?

Hey there, I'm wondering if it's possible to convert a Map to JSON and back again using GSON. The object I'm working with has already been converted from JSON to an Object using GSON. The structure of the object I'm using is as follow ...

Cannot see the template on the Angular Typescript component

After encountering and resolving this issue: AngularJS directive not displaying the template I decided to experiment with an Angular component and TypeScript, but unfortunately, I can't seem to make it work. The component refuses to display. This is ...

Making tinymce editor content readonly using Angular 4

In my Angular 4 form, I am utilizing two editors. To make the editors readonly, I have implemented the following code: tinymce.activeEditor.getBody().setAttribute('contenteditable', false); tinymce.activeEditor.getBody().style.backgroundColor = ...

Leveraging LESS in an Angular2 component

Currently, I am attempting to integrate LESS with angular2. To do so, I have imported the less.js file in my index.html and I am using the following command within the component: less.modifyVars({ '@currentTheme-bar': '@quot ...

The console is displaying an undefined error for _co.photo, but the code is functioning properly without any issues

I am facing an issue with an Angular component. When I create my component with a selector, it functions as expected: it executes the httpget and renders a photo with a title. However, I am receiving two errors in the console: ERROR TypeError: "_co.photo ...

Unable to make changes to the document

Having trouble updating a document by ID using mongoose and typescript. I'm testing the api and passing the id as a parameter. I've experimented with different methods of updating by ID, but for some reason, it's not working. Can update by ...

The number associated with the 'pipe' is currently unavailable

After successfully migrating my application from Angular 4 to 7, I encountered an issue during compilation (ng build --prod). The error message displayed was: ERROR in : Template parse errors: The pipe 'number' could not be found (" </d ...

Ways to implement distinct service instances for several child components in Angular 2

I have been working on an application that features multiple instances of a similar master-details view along with a search box. To streamline the process, I decided to create a separate module for this common functionality and establish communication betw ...

Compilation in TypeScript taking longer than 12 seconds

Is anyone else experiencing slow TypeScript compilation times when building an Angular 2 app with webpack and TypeScript? My build process takes around 12 seconds, which seems excessively slow due to the TypeScript compilation. I've tried using both ...

Tracking button clicks on Angular Material using Google Analytics through Google Tag Manager

I'm currently utilizing the Universal Analytics tag within Google Tag Manager to monitor user interactions. I'm looking to establish click listeners in GTM that will trigger when specific buttons on the page are clicked. These buttons are Angular ...

What is the correct way to import scss files in a Next.js project?

Currently, I am working on a NextJS project that uses Sass with TypeScript. Everything is running smoothly in the development environment, but as soon as I attempt to create a build version of the project, I encounter this error. https://i.stack.imgur.com ...

Adding a unique font to the themeprovider within styled components: A step-by-step guide

In the process of developing a React application using material-ui styled-components along with TypeScript. The task at hand is to incorporate a custom font into my styled components, but I'm facing challenges in making it functional. My initial ste ...

Divide the string into several segments according to its position value

Here is a piece of text that I would like to divide into multiple sections, determined by the offset and length. If you have any questions or comments and would like to get in touch with ABC, please go to our customer support page. Below is a function ...

Require that the parent FormGroup is marked as invalid unless all nested FormGroups are deemed valid - Implementing a custom

Currently, I am working on an Angular 7 project that involves dynamically generating forms. The structure consists of a parent FormGroup with nested FormGroups of different types. My goal is to have the parentForm marked as invalid until all of the nested ...