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

Error TS2488 in React TypeScript: The data type 'IStateTypes' is required to have a method called '[Symbol.iterator]()' that returns an iterator

At the moment, I am working on implementing a global state in React Hooks but have run into an issue. https://i.stack.imgur.com/DN83K.png The current problem I'm facing is with [Symbol.iterator](. I am uncertain about how to resolve this as I am in ...

Typescript error in RxJS: Incorrect argument type used

I came across this code snippet from an example in rxjs: Observable.fromEvent(this.getNativeElement(this.right), 'click') .map(event => 10) .startWith({x: 400, y: 400}) .scan((acc, curr) => Object.assign({}, acc, {x: acc ...

Is Typescript compatible with the AWS Amplify Express API?

I've been struggling to set up my Amplify API in TypeScript and then transpile it to JavaScript. I know it sounds like a simple process, but I could really use some guidance on how to do this effectively. So far, I haven't progressed beyond the ...

I am looking to insert an array of a specific type into a Postgres database using Node.js, but I am unsure of the process

query.callfunction('fn_create_mp_product', parameters, (err, result) => { if (err) { console.log(err) callback(err); } else { if (result.status == 'success') { callb ...

When configuring the Redux logger, the type 'Middleware<{}, any, Dispatch<UnknownAction>>' is not compatible with type 'Middleware<{}, any, Dispatch<AnyAction>>'

In my React project, I have defined the redux logger with the package version "redux-logger": "^3.0.6" in the file store.ts as shown below: import { configureStore } from '@reduxjs/toolkit'; import rootReducer from '@/re ...

The unfamiliar module 'Ng2SmartTableModule' was unexpectedly declared within the 'AppModule'

I am currently exploring ng2 smart table through this link and encountering an error. An unexpected module 'Ng2SmartTableModule' was declared by the module 'AppModule', resulting in the following error: Uncaught Error: Unexpected modul ...

Combine several php arrays into a single array

I want to generate a series of arrays that follow this structure: Array ([ID] => 55 [status] => u [resvdate] => 07/16/2018 [price] => 119.00 [source] => C) Array ([ID] => 56 [status] => u [resvdate] => 07/17/2018 [price] => 119 ...

Examining interconnected services' dependencies

Looking to test out AService, which has dependencies on BService and CService. The dependency chain looks like this: AService --> BService --> CService The constructor for AService is as follows: constructor( private bService: BService ) {} The const ...

Observable emitting value after execution of method

Why does the getModel() method always return an array with empty name arrays even when the languages Observable returns a value? export interface Category extends BaseModel { code: string; name: LocalizedValue[]; description: Local ...

What is the best way to center align the placeholder in an ion-input field?

What is the best way to center align the placeholder in ion-input? Here's a screenshot of my current ionic input fields with left alignment. I've attempted to move the alignment to the center, but I've been unsuccessful. Can someone please ...

Running Angular/Rxjs store (ngrx) calls synchronously

After fetching 2 items from my store using ngrx, I need both requests to complete before taking further action. Here's an example of what I'm trying to achieve: const item1$: Observable<Item> = this._store$.select( ItemStoreSelectors.sele ...

Routing in Angular app breaks down after selecting a single route

I'm new to Angular and currently working with the Router module. I have a Servers component with 3 servers, and clicking on each server should open the individual server's component on the same page. However, I've encountered an issue where ...

What specific event do I require for the onChange event in React using TypeScript?

I'm facing a problem while working with React TypeScript. I need to type the onChange event for a select element, but the data is coming from event.value instead of event.target.value. What should be the appropriate event to use in this case? Below i ...

The compatibility issues between Karma and Jasmine testing configurations cause errors during the Ionic packaging process

I've recently added testing to my ionic app using karma + jasmine, along with a typescript pre-processor. Below are the dependencies I have, most of which were added specifically for testing: "devDependencies": { "@ionic/app-scripts": "1.0.0", ...

The element class type 'xxx' is lacking several properties compared to the 'ElementClass' type, including context, setState, forceUpdate, props, and others. This issue is flagged with error code TS2605

Encountering an error while attempting to execute my react app: D:/React/my-components/src/App.tsx TypeScript error in D:/React/my-components/src/App.tsx(23,4): JSX element type 'Confirm' is not a constructor function for JSX elements. ...

Retrieving the value from a string Enum in Angular based on an integer

export enum RoleTypesEnum { RoleA = 'Role is A', RoleB = 'Role is B', } // in TypeScript file public RoleTypesEnum = RoleTypesEnum; I am trying to obtain the string value (e.g. Role is B) from an enum using an integer. If I u ...

Tips for packaging a Node TypeScript/JavaScript library using Webpack

I am currently working on a Node project with the following setup: Written in Typescript Using Webpack and ts-loader for bundling Targeting Node.js +-proj/ +-src/ |-file1.ts |-file2.ts |-file3.ts |-... |-package.json |-webpack.confi ...

Guide to altering the characteristics of a button

Here is the code for a button within My Template: <div *ngFor="let detail of details" class = "col-sm-12"> <div class="pic col-sm-1"> <img height="60" width="60" [src]='detail.image'> </div> <div ...

Working with floating point numbers in Node.js with a zero decimal place

NodeJS interprets float values with a zero after the decimal point as integers, but this behavior occurs at the language level. For example: 5.0 is considered as 5 by NodeJS. In my work with APIs, it's crucial for me to be able to send float values w ...

The element 'mat-tab' does not recognize the property 'active', therefore it cannot be bound

I keep encountering this error even though I have already imported MatTabsModule. Below is the structure of my component: @Component({ selector: 'app-settings-page', template: ` <mat-tab-group animationDuration="0ms"> <mat-tab *n ...