Retrieve an array of information and convert it into an object using Angular

My previous data is displaying correctly in the chart, as shown below:

@Component({
 selector: 'app-inpout-bar-chart',
 templateUrl: './inpout-bar-chart.component.html',
 styleUrls: ['./inpout-bar-chart.component.scss']
})
export class InpoutBarChartComponent implements OnInit {

saleData = [
{ name: 'Mozafati', value: 105000 },
{ name: 'piarom', value: 55000 },
{ name: 'rabbi', value: 15000 },
{ name: 'zahedi', value: 150000 },
{ name: 'Kalteh', value: 20000 }
];
constructor() { }
 ngOnInit(): void {
  }
}

Now, I want to assign new data from arrays productsName and productsValue to Saledata.

  productsName = ['Mozafati', 'piarom', 'rabbi' , 'zahadi', 'Kaliteh' ];
 productsValue = ['2000', '15000', '1500' , '5500', '10500' ]; 

 productData: any[] = [
  {name: this.productsName, value: this.productsValue}
  ];

However, this approach is not working. How can I set ProductName and productValue to Saledata?

Update:

After receiving a comment and answer, the code has been updated as follows:

export class InpoutBarChartComponent implements OnInit {

productsName = ['mozafati', 'piarom', 'rabbi' , 'zahedi', 'kaliteh' ];
productsValue = ['2000', '15000', '1500' , '5500', '10500' ];

saleData: any[];

setData(){
 for (const i in this.productsName) {
  this.saleData.push({
    name: this.productsName[i],
    value: this.productsValue[i]
  });

 }
 }
constructor() { }

ngOnInit(): void {

this.setData();
console.log(this.saleData);
}
}

The HTML component now includes:

<ngx-charts-bar-vertical
[view]="[1000,400]"
[results]="saleData"
[xAxisLabel]="'product'"
[legendTitle]= "'number'"
[yAxisLabel]= "'value of product'"
[legend]="true"
[showXAxisLabel]="true"
[showYAxisLabel]="true"
[xAxis]="true"
[yAxis]="true"
[gradient]="true">
</ngx-charts-bar-vertical>

Upon adding console.log, an error message was displayed:

Cannot read property 'push' of undefined

Answer №1

If you are looking to assign values in a specific order based on arrays (for instance, pairing 'Mozafati' with '2000'), you can use the following approach:

fruits = ['apple', 'banana', 'kiwi' , 'pear', 'melon'];
calories = ['100', '150', '50' , '90', '120']; 

setData() {
    for (let j in this.fruits) {
        this.nutritionData.push({
            name: this.fruits[j],
            calories: this.calories[j]
        })
    }
}

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

Validation of dynamic fields in a reactive form is malfunctioning specifically for the <Select> element

My form includes a reactive form with a form array, where clicking a button adds a new form group to the array. Upon form submission, I want to validate if these dynamic fields are empty. However, room.errors?.required does not seem to execute as expected ...

Choose a specific interface in Typescript

I am interested in developing a React alert component that can be customized with different message colors based on a specific prop. For example, I envision the component as <alert id="component" info/> or <alert id="component" ...

Obtain a collection of keys that share identical values

In my JavaScript code, I have an array of objects structured like this: objArray = [ {"date":"07/19/2017 12:00:00 AM","count":"1000","code":"K100"}, {"date":"07/21/2017 12:00:00 AM","count":"899","code":"C835"}, {"date":"07/23/2017 12:00:00 AM","cou ...

Tips for determining the defaultValue type in React.context usage

'use client'; import { useState, createContext, useMemo } from 'react'; type MessageStatus = 'default' | 'success' | 'error'; export type MessageProps = { type: MessageStatus; payload: string; }; ty ...

Storing Json data in a variable within Angular 2: a step-by-step guide

Within the params.value object, there are 3 arrays containing names that I need to extract and store in a variable. I attempted to use a ForEach loop for this purpose, but encountered an issue. Can you spot what's wrong? var roles = params.forEach(x ...

What is the best way to retrieve a value from an array?

Using ASP.net Core, I receive information from my API. In Angular, the data looks like this: 0: {Id: 3, Role_Name: 'ITAdmin'} 1: {Id: 4, Role_Name: 'Admin'} 2: {Id: 5, Role_Name: 'user'} I want to extract values from this arr ...

What is the relationship between directives, templates, and ViewContainers in Angular?

I have implemented a basic functionality in my component where numbers are injected after a delay using a custom directive called *appDelay It is known that the Angular syntax hints with * will de-sugar into something like this: <ng-template ...> .. ...

Mastering the Conversion from NGRX Effect to NGRX Effect v15

I am currently working on converting the code snippet to NGRX 15. As a newcomer to Angular, I could use some guidance. "@ngrx/effects": "^15.4.0" @Injectable() export class SnackbarEffects { @Effect({ dispatch: false }) cl ...

Is it possible to apply two ngClass directives to a single div element in Angular 4?

When I click to start editing, a component is called for the editing process. In this component, I am unable to click on anything and the background turns black, which is okay. However, I would like for each ID that I select to edit to become active with a ...

Tips for showcasing the CDK table in Angular without duplicating customer IDs

My CDK table is used to display data, but I am facing an issue with duplicated data in the dataSource as shown below: [ {customerID:"56789", name: "foo", mobile: "123456"}, {customerID:"56789", name: "foo", mobile: "123456"}, {customerID:"12345", name: "f ...

The issue of TypeScript failing to return HTML Template Element from Constructor typing is causing complications

There is a restriction on using new to create an instance of Template, which extends an HTMLTemplateElement. To work around this limitation, I fetch and return an HTMLTemplateElement by using document.getElementById(id) within the constructor of the Templ ...

Unable to initialize default values on Form Load in Angular Reactive Forms

My goal is to make an HTTP request by passing an ID, then take the response and assign the values to form fields. I attempted using setValue and patchValue methods, but they did not yield the desired results. spService itemData = new ItemData() getIte ...

Angular error TS2322 arises when attempting to assign a type of 'Observable<{}>' with the share() operator

Currently diving into Angular 5, I've been exploring the Observable/Observer pattern to facilitate event sharing and data changes among subscribers. Below is a snippet of the code in question: ... @Injectable() export class NidoService { ... eve ...

The power of Angular 18's new @let syntax for template rendering

The latest update from the Angular team introduces a new @let syntax in templates. As mentioned in this comment, this feature is now available in this commit, which has been rolled out in version 18.0.2. I have updated my NX workspace to use @angular/comp ...

Sending the :id parameter to the Service component

In the early days of my Angular journey, I have a simple question. Currently, I am utilizing the WordPress REST API to showcase a list of posts from a specific category by using posts?categories={ID HERE}. However, I am facing an issue in passing the ID f ...

Combining URL parameters into an object with NestJS's HTTP module

Is there a method for passing URL parameters to the httpService in nestjs? I want to improve the readability of this URL without resorting to Axios as nest has its own HTTPModule. Currently, this is how it looks and functions: const response = await this. ...

The Order ID field in the Serenity-Platform's Order Details tab is not registering orders

I've been working on replicating the functionality of Orders-Order detail in my own project. https://i.stack.imgur.com/Bt47B.png My custom module is called Contract and Contract Line item, which I'm using to achieve this. https://i.stack.imgur ...

Exploring the Latest Features: Using Angular 7 with Bootstrap Collapse for Dynamic Aria-Controls

I am currently working on creating my own component to use within an *ngFor loop. I am facing an issue where I need a unique value for my Collapse feature. Right now, when I click on the second main row in the table, the collapse feature only shows the inn ...

Is there a way to enable code completion for Firebase on VS Code?

After successfully setting up Typescript for code completion following the guidelines provided in this resource, I now want to enable code completion for Firebase in VS Code. However, I am unsure of the steps to achieve this. How can I activate code compl ...

Can you explain the distinction in C++ between new and new[] when it comes to allocating arrays?

In my understanding, there is a difference in memory allocation and deallocation between C and C++. In C, malloc/free can handle both single objects and arrays seamlessly, while in C++, new/delete and new[]/delete[] pairs need to be used accordingly. Acco ...