Creating a Complex Object in Angular 5: A Step-by-Step Guide

Currently, I am constructing an object that will contain a key and its corresponding values:

const colorRedCodes = this.orderInProgressCmsModel.orderStatusColorRed.split(",");
const colorGreenCodes = this.orderInProgressCmsModel.orderStatusColorGreen.split(",");

const testObject = { colorName: "", colorCodes: []};

To populate the object with information, I have implemented the following steps:

testObj.colorName = "red";
testObj.colorCodes = colorRedCodes;
testObj.colorName = "green";
testObj.colorCodes = colorGreenCodes;

However, this method ends up only storing the last two sets of data due to overwriting.

The main objective here is to optimize the code by reducing the number of conditional statements (if's) and achieve the same outcome with a more logical approach if feasible:

if(colorRedCodes.some(s => s.includes(code))){
  this.orderStatusColor = JSON.parse('{"color": "red"}');
}

if (colorGreenCodes.some(s => s.includes(code))){
  this.orderStatusColor = JSON.parse('{"color": "green"}');
}

if (colorBlackCodes.some(s => s.includes(code))){
  this.orderStatusColor = JSON.parse('{"color": "black"}'); 
}

Answer №1

Transform testObj into an array and add the values to it as shown:

const testObj = [];
let newItem = {type: 'shirt', size: 'medium'}

testObj.push(newItem);

Answer №2

After taking some time to reconsider, I realized that what I actually required was an Array of Objects. Here's how I implemented it:

const testObj: Array<{ colorName: string, colorCodes: string[] }> = [
      { "colorName": "red", "colorCodes": codeRed },
      { "colorName": "green", "colorCodes": codeGreen },
      { "colorName": "black", "colorCodes": codeBlack }
    ];

By doing this, the result looks like this:

(3) [{…}, {…}, {…}]
0:
    colorName: "red"
    colorCodes: (3) ["2", "3", "8"]
__proto__: Object
1:
    colorName: "green"
    colorCodes: (3) ["0", "1", "7"]
__proto__: Object
2:
    colorName: "black"
    colorCodes: (4) ["4", "5", "6", "9"]
__proto__: Object
length: 3
__proto__: Array(0)

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

What is the function of the 'this' keyword within a Vue component?

Can someone explain how the keyword 'this' is able to access tasks that are not within the same object? anyobject = { template: '#task-list', props: { tasks: {default: []} }, data() { return { newTask: '&apos ...

IONIC is displaying an error message indicating that there is no provider available for MapsAPIL

I am trying to implement a search feature with a Google map in my Ionic/Angular project. However, I encountered the following error: Runtime Error No provider for MapsAPILoader! Stack Error: No provider for MapsAPILoader! at inje ...

Regular expressions help eliminate extra spaces and any spaces that occur before characters

I am currently working on creating a regular expression to ensure there are no double spaces in a string, while also requiring a single space before the characters MO or GO, with no spaces allowed at the start or end of the string. Example 1: It is 40 GO ...

How can I clear the defaultValue attribute for an input field when submitting a form?

I created a component with the following code: import * as React from 'react'; const taskAdd = (props: { handleAdd: any }) => { return ( <form className="form-inline" onSubmit={props.handleAdd}> <tab ...

Angular 9 - Refresh page while redirecting to the same URL, triggering only the API call specific to the current page

Is there a way to redirect to the same URL and also refresh the page without calling all APIs from the beginning of the application? I have attempted using an anchor tag with href, but it results in refreshing the entire page and fetching all APIs again. I ...

Utilizing dynamic arguments in TypeScript to recycle types

Can I accomplish this with TypeScript? Here is the source code I currently have: interface FormStore<T> { type: T; } interface Form<T> extends FormStore<T> { email: T; phone: T; password: T; } interface FormState<R> { fo ...

Here's how to use the useState hook directly in your React components without

Currently, I am using the code snippet below to import useState: import * as React from 'react' import {useState} from 'react' I wanted to see if there is a way to condense this into one line, so I attempted the following: import * a ...

Triggering a client-side dialog in Electron-Angular upon receiving an IPC event

I am experiencing a strange issue with my back-end notification system and client-side Angular Material dialog component. There are times when the dialog does not fully instantiate, even though the constructor of the component is invoked. The component&apo ...

Implement tooltip functionality in ssr chart using echarts

A chart is generated using echarts on the server-side: getChart.ts const chart = echarts.init(null, null, { renderer: 'svg', ssr: true, width: 400, height: 300 }); chart.setOption({ xAxis: { data: timeData }, ...

Playing with an array of objects

How can we modify an array of objects in Angular Typescript by replacing certain values and adding new key-value pairs? I need to swap the id value with memberId and then introduce a new key fullName that combines firstName and lastName. Any suggestions ...

The values obtained from an HTTP GET request can vary between using Curl and Ionic2/Angular2

When I make a GET request using curl in the following manner: curl https://api.backand.com:443/1/objects/todos?AnonymousToken=my-token I receive the correct data as shown below: {"totalRows":2,"data":[{"__metadata":{"id& ...

Guide on utilizing mat-slide-toggle to assign either a value of 1 or 0

I am utilizing the mat-slide-toggle feature from Material in a similar manner to this example https://material.angular.io/components/slide-toggle/overview The problem I am encountering is similar to the issue outlined in this link: https://stackblitz.com ...

Struggling to locate the element needed to create an if statement

Unable to locate a specific element that I want to include in an if statement: (EDIT) from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.keys import Keys from selenium.common.exce ...

Ensure the object is not null with this Object type guard

Is there a way to create a type guard for an object directly in TypeScript? I've written a function to check any input: export function isObject(input: any) :input is Record<string,any> { return (input !== null) && (typeof input == ...

Prevent time slots from being selected based on the current hour using JavaScript

I need to create a function that will disable previous timeslots based on the current hour. For example, if it is 1PM, I want all timeslots before 1PM to be disabled. Here is the HTML code: <div class=" col-sm-4 col-md-4 col-lg-4"> <md ...

How can you utilize a variable as 'othername' instead of 'var' using const in Javascript or Typescript?

Is there a better way to achieve the following: const { colors as ThemeColors } = useTheme(); I'm trying to avoid doing it like this: const { colors } = useTheme(); const ThemeColors = colors; If you have any suggestions, please let me know. Thanks! ...

Using an existing function with no arguments as a handler in Typescript and React: A Step-by-Step Guide

NOTE: I'm still learning Typescript, so I may be missing something obvious here. Let's consider a basic scenario in React Javascript, using a Material-UI Button: // Closing dialog event handler without needing an 'event' argument const ...

Discovering the specific p-checkbox in Angular where an event takes place

Is there a way to assign an ID to my checkbox element and retrieve it in my .ts file when the checkbox is selected? I want to pass this ID along with the true or false value that indicates if the checkbox is checked. Here's an example code snippet: &l ...

Avoiding the inclusion of server-side modules in the webpack build process for a client-side application

I specialize in developing web applications using NodeJS and React. Lately, I've been experimenting with different architecture styles and I'm currently fascinated by the concept of sharing code between the server-side and client-side. I believe ...

The filter function results in a blank array being returned

I'm facing a dilemma, I have a constant defined as export const STATUS = [{ 0: 'Draft', 1: 'Sent', 2: 'Processing', 9: 'Processed', 3: 'Scheduled', 4: 'Filed', 5: 'Suspende ...