Create Array from objects in angular js - arrays

I am new in this framework. I want to convert objects into array in angular 8. But I don't get how this work.
Actually, I want to display multiple sales transactions of the a customer with status false.
So, somehow I get the values of those transaction made by the same customer as a separate different objects.
Now, I want to convert those objects into a single array so that I can iterate them in html file through *ngFor.
export class InvoicesComponent implements OnInit {
displayedColumns: string[] = ['ProductName', 'CustomerName', 'Quantity',
'Rate', 'Total'];
id;
dataSource;
salesTransaction: SalesTransactionElement[];
constructor(private service: SalesTransactionsService,
private route: ActivatedRoute)
{ }
ngOnInit() {
this.id = this.route.snapshot.paramMap.get('id');
this.service.getSalesTransaction(this.id).subscribe((singleData: any) =>
{
this.service.getAllSalesTransactions().subscribe((data: any) =>
{
data.forEach(element =>
{
if (singleData.CustomerName === element.CustomerName &&
element.Status === false) {
this.salesTransaction = element;
console.log(this.salesTransaction);
}
});
});
}
Actual Results:
/*****Separately as two objects****/
{SalesTranId: 54, ProductId: 10, CustomerId: 21, InvoiceId: null, ProductName: "Asus"}
{SalesTranId: 51, ProductId: 17, CustomerId: 21, InvoiceId: 1, ProductName: "Dell"}
Expected Results:
/**********Array of Objects************/
[{SalesTranId: 54, ProductId: 10, CustomerId: 21, InvoiceId: null, ProductName: "Asus"},
{SalesTranId: 51, ProductId: 17, CustomerId: 21, InvoiceId: 1, ProductName: "Dell"}]

Initialize the array above the constructor: salesTransaction: SalesTransactionElement[] = []
Then push into that array in your forEach handler: this.salesTransaction.push(element);

Actually you are assigned an object in your array definition of SalesTransactionElement[] so you need to push a SalesTransactionElement.
export class InvoicesComponent implements OnInit {
displayedColumns: string[] = ['ProductName', 'CustomerName', 'Quantity',
'Rate', 'Total'];
id;
dataSource;
salesTransaction: SalesTransactionElement[];
constructor(private service: SalesTransactionsService,
private route: ActivatedRoute)
{ }
ngOnInit() {
this.id = this.route.snapshot.paramMap.get('id');
this.service.getSalesTransaction(this.id).subscribe((singleData: any) =>
{
this.service.getAllSalesTransactions().subscribe((data: any) =>
{
data.forEach(element =>
{
if (singleData.CustomerName === element.CustomerName &&
element.Status === false) {
this.salesTransaction.push(element);
}
});
});
}

Related

Merge new object in firebase database inside document

I have stored my data into firebase database by getting data from google sheet. The problem I am getting is every time I run the application It sets with new document Id. I want only one document in the firebase database collection.
My question is How do I merge data when I get new data object as response?
Example:
I have got following response :
0: {Id: 202, Name: 'word', Major: 'comp'}
1: {Id: 203, Name: 'John', Major: 'science'}
2: {Id: 204, Name: 'nsia', Major: 'cmpi'}
and It is stored in database.
Now when I run application again then It creates new document instead of merging new data to old document.
Example:
new data is
0: {Id: 205, Name: 'hello', Major: 'sci'}
and I want to merge object and get as
0: {Id: 202, Name: 'word', Major: 'comp'}
1: {Id: 203, Name: 'John', Major: 'science'}
2: {Id: 204, Name: 'nsia', Major: 'cmpi'}
3: {Id: 205, Name: 'hello', Major: 'sci'}
How do we do merge?
Here is my code to get data and post data
import { HttpClient } from '#angular/common/http';
import { Component, OnInit } from '#angular/core';
import { AngularFirestore, AngularFirestoreCollection } from '#angular/fire/compat/firestore';
import { Router } from '#angular/router';
import { AuthService } from '../shared/auth.service';
import { Field } from '../model/field';
#Component({
selector: 'app-landing-page',
templateUrl: './landing-page.page.html',
styleUrls: ['./landing-page.page.scss'],
})
export class LandingPagePage implements OnInit {
Object = Object;
myArray: Field[] = [];
private collection: AngularFirestoreCollection<Field>;
myCollection: any;
constructor(private auth: AuthService, private router:Router, private http :HttpClient,private afs: AngularFirestore) {
this.collection = this.afs.collection<Field>("Exceldata");
this.myCollection = this.collection.snapshotChanges();
}
ngOnInit() {
this.excelData();
this.auth.getDataFromFirebase().subscribe(myArray => {
this.myArray = myArray;
});
}
logout()
{
this.auth.signOut();
}
excelData(){
var sf = "https://docs.google.com/spreadsheets/d/1qeCEUlVt_hnuyhnoT1wxMMSv7kZW1s4cUIRLynJ0TxQ/gviz/tq?tqx=out:json";
this.http.get(sf,{responseType: 'text'}).subscribe(res=>{
const data =res.toString().match(/google\.visualization\.Query\.setResponse\(([\s\S\w]+)\)/);
if(data && data.length==2){
const obj=JSON.parse(data[1]);
const table=obj.table;
const header = table.cols.map(({label}) => label);
const rows = table.rows.map(({c}) => c.map(({v}) => v));
const values = rows.map(e => header.reduce((o, f, j) => Object.assign(o, {[f]: e[j]}), {}));
console.log(values);
if(!this.collection.doc){
this.collection.doc().set(Object.assign({}, values));
}else{
this.collection.doc().set((values),{merge: true});
}
}
});
}
I'm not sure if there's a better way of doing it but I've survived by storing my items locally eg as an array, appending new item and then saving as a new item.

How to store values from a service to an array in Angular?

I have a service with getter and setter methods, they return me id: number and title: String from my dialog component.
I need to store the values from the response to my data array, but I just cant figure out how.
For example:
0: {id: 0, title: "UK ",…}
1: {id: 1, title: "Usd ",…}
2: {id: 2, title: "ff ",…}
3: {id: 3, title: "yy ",…}
4: {id: 4, title: "nn ",…}
5: {id: 5, title: "mh ",…}
6: {id: 6, title: "tr ",…}
7: {id: 7, title: "es ",…}
I would be so grateful if you guys can help me out.
Here is what I got so far:
app.component.ts
export class AppComponent {
clickEventsubscription: Subscription
ngOnInit() {
}
id: number;
title: String;
data: any = [];
constructor(private share: ShareDataService) {
this.clickEventsubscription = this.share.getClickEvent().subscribe(() => {
this.initialize();
})
}
initialize() {
this.id = this.share.getId();
this.title = this.share.getTitle();
console.log(this.id, this.title);
}
}
app.component.html
<app-dialog></app-dialog>
<h2>Add values of my service into array:</h2>
<button (click)="initialize()"></button>
share-data.service.ts
import { Injectable } from '#angular/core';
import { Observable, Subject } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class ShareDataService {
title: String;
id: number;
getId() {
return this.id
}
getTitle() {
return this.title;
}
private subject = new Subject<any>();
sendClickEvent() {
this.subject.next();
}
getClickEvent(): Observable<any> {
return this.subject.asObservable();
}
}
Many thanks!
As far as I understand your question, there are several solutions to solve this
but the simplest way is to create an new object every time you trigger the initialize method which goes as follows
change this
initialize() {
this.id = this.share.getId();
this.title = this.share.getTitle();
console.log(this.id, this.title);
}
to the following
initialize(): void {
this.id = this.share.getId();
this.title = this.share.getTitle();
const newData = {
id: this.id,
title: this.title
};
this.data.push(newData);
}
There are some syntax errors and ordering issue in your code both the service and app component which should be solved (depends on what version of angular you are using).
Also you have to declare instant fields before instance declaration of instance method, this should come at the beginning of the class/interface
move this to the top of your class in share-data.service.ts
private subject = new Subject<any>();

How to iterate through nested object in Angular 2 using Type Script?

Hi I am developing web application using Angular 2. I am receiving JSON data using API. I am trying to segregate data. Below is my JSON data.
[
{
"userid":"f8b7b393-b36d-412b-82f7-9500e9eb6924",
"tenantid":"7a4a4ea9-3b39-4ef6-8d00-fcfe7454888c",
"username":"testuser3",
"emailaddress":"testuser3#rkdssravioutlook.onmicrosoft.com",
"isallowed":false,
"userroles":[
{
"userroleid":"c4c64675-ffe0-467b-87a4-00b899e0d48e",
"userid":"f8b7b393-b36d-412b-82f7-9500e9eb6924",
"roleid":"ada09fb2-fa83-4e46-8878-7e4e48c73111",
"tenantappid":1,
"validfrom":"2018-01-24T00:00:00",
"validto":"2018-01-24T00:00:00",
"isactive":true,
"isdeleted":false,
"role":{
"roleid":"ada09fb2-fa83-4e46-8878-7e4e48c73111",
"rolename":"Installer",
"tenantid":"99999999-9999-9999-9999-999999999999",
"isactive":true,
"isdeleted":false,
"actionnames":null,
"scopeids":null,
"scopes":null,
"actionids":null,
"actions":null
}
},
{
"userroleid":"bf632c7b-7540-479e-b8ec-b1471efd7f93",
"userid":"f8b7b393-b36d-412b-82f7-9500e9eb6924",
"roleid":"80dc8c6a-a934-4c2e-9d17-7cdd5b774fc6",
"tenantappid":1,
"validfrom":"2018-01-24T00:00:00",
"validto":"2018-01-24T00:00:00",
"isactive":true,
"isdeleted":false,
"role":{
"roleid":"80dc8c6a-a934-4c2e-9d17-7cdd5b774fc6",
"rolename":"Operator",
"tenantid":"99999999-9999-9999-9999-999999999999",
"isactive":true,
"isdeleted":false,
"actionnames":null,
"scopeids":null,
"scopes":null,
"actionids":null,
"actions":null
}
}
]
},
{
"userid":"8363def7-7547-425c-8d55-2116dd703cfc",
"tenantid":"7a4a4ea9-3b39-4ef6-8d00-fcfe7454888c",
"username":"testuser1",
"emailaddress":"testuser1#rkdssravioutlook.onmicrosoft.com",
"isallowed":false,
"userroles":[
{
"userroleid":"fe2b1f9f-4cd8-48dc-9708-2637e9743c1d",
"userid":"8363def7-7547-425c-8d55-2116dd703cfc",
"roleid":"ada09fb2-fa83-4e46-8878-7e4e48c73111",
"tenantappid":1,
"validfrom":"2018-01-24T00:00:00",
"validto":"2018-01-24T00:00:00",
"isactive":true,
"isdeleted":false,
"role":{
"roleid":"ada09fb2-fa83-4e46-8878-7e4e48c73111",
"rolename":"Installer",
"tenantid":"99999999-9999-9999-9999-999999999999",
"isactive":true,
"isdeleted":false,
"actionnames":null,
"scopeids":null,
"scopes":null,
"actionids":null,
"actions":null
}
}
]
},
{
"userid":"7f359233-5940-4b93-8ec9-fcf39e2fb58f",
"tenantid":"7a4a4ea9-3b39-4ef6-8d00-fcfe7454888c",
"username":"testuser2",
"emailaddress":"testuser2#rkdssravioutlook.onmicrosoft.com",
"isallowed":false,
"userroles":[
{
"userroleid":"c479b1c0-5275-40b2-893e-fc82dc55f1a5",
"userid":"7f359233-5940-4b93-8ec9-fcf39e2fb58f",
"roleid":"4dd2803b-e723-4356-8381-7c514ba13247",
"tenantappid":1,
"validfrom":"2018-01-24T00:00:00",
"validto":"2018-01-24T00:00:00",
"isactive":true,
"isdeleted":false,
"role":{
"roleid":"4dd2803b-e723-4356-8381-7c514ba13247",
"rolename":"Engineer",
"tenantid":"99999999-9999-9999-9999-999999999999",
"isactive":true,
"isdeleted":false,
"actionnames":null,
"scopeids":null,
"scopes":null,
"actionids":null,
"actions":null
}
}
]
}
]
Below are my corresponding models.
export class UserModel {
public userid: string;
public tenantid: string;
public isallowed: boolean;
public emailaddress: string;
public upn: string;
public userroles: UserRole[];
public roleid: string;
public isactive: boolean;
public tenantappid: string;
public username: string;
public userrolestext: string;
public validfrom: string;
public validto: string;
}
Below is role model
export class UserRole {
public userid: string;
public roleid: string;
public role: Role;
}
Below is the sample data i am trying to get
[
{
"userid":"f8b7b393-b36d-412b-82f7-9500e9eb6924",
"tenantid":"7a4a4ea9-3b39-4ef6-8d00-fcfe7454888c",
"rolename":"Installer",
"rolename":"Operator",
},
{
//rest of the data
}
]
First array of above object contains userid and below it contains again array of userroles. So i am trying to get each rolename associated with userid in a single row.
Below code i tried.
users.forEach(eachObj => {
eachObj.userroles.forEach(nestedeachObj => {
});
});
I am not able to go forward in the above foreach loop. Can someone help me to segregate above data? Any help would be appreciated. Thank you.
Hey I really don't know if my code example will achieve what you are looking for but what my example is creating looks like this:
RESULT:
[
{
tenantid: "7a4a4ea9-3b39-4ef6-8d00-fcfe7454888c",
userid: "f8b7b393-b36d-412b-82f7-9500e9eb6924",
rolename: "Operator"
},
{
tenantid: "7a4a4ea9-3b39-4ef6-8d00-fcfe7454888c",
userid: "8363def7-7547-425c-8d55-2116dd703cfc",
rolename: "Installer"
},
{
tenantid: "7a4a4ea9-3b39-4ef6-8d00-fcfe7454888c",
userid: "7f359233-5940-4b93-8ec9-fcf39e2fb58f",
rolename: "Engineer"
}
]
CODE:
const getRelevantData = (array) => {
data.forEach((user) => {
const obj = {};
obj.tenantid = user.tenantid;
obj.userid = user.userid;
user.userroles.forEach((userrole) => {
obj.rolename = userrole.role.rolename;
});
array.push(obj);
});
};
I have added below code and worked fine.
this.userroleData = [];
results.forEach(eachObj => {
eachObj.userroles.forEach(nestedeachObj => {
this.userroleData.push({
username: eachObj.username,
userrolestext: nestedeachObj.role.rolename,
});
});
});

Typescript Array - Splice & Insert

I have 3 arrays here of type channel array.
currentPickSelection: Array<channel>;
draggedChannel: channel;
droppedChannel: channel;
What I am trying to do is remove an item(the droppedChannel array item)from the currentPickSelection array and insert the draggedChannel item array onto the same index of the removed item.
Here is what I did so far, everything works except the insert part:
let index = this.currentPickSelection.findIndex(item => item === this.droppedChannel);
this.currentPickSelection.splice(index, 1, this.draggedChannel);
An this is the way I have the channel model declared:
export class CompChannel {
constructor(public compChannelCbsCode: string,
public compChannelName: string,
public compChannelLogo: string) {}
}
export class channel {
public pickCode: string;
public cbsCode: string;
public channel: string;
public logo: string;
public compChannel: CompChannel[];
constructor(pickCode: string, cbsCode: string, channel: string,
logo: string, compChannel: CompChannel[]) {
this.pickCode = pickCode;
this.cbsCode = cbsCode;
this.channel = channel;
this.logo = logo;
this.compChannel = compChannel;
}
}
Please advise what is wrong!
The droppedChannel object and the item found in currentPickSelection may not the exact same copy/clone of each other.
Try to compare with an unique value(like pickCode or cbsCode) in findIndex method instead of comparing with the whole object.
let currentPickSelection: any[] = [
{ id: 1, label: 'Test1' },
{ id: 2, label: 'Test2' },
{ id: 3, label: 'Test3' }
];
let draggedChannel: any = { id: 5, label: 'Test5' };
let droppedChannel: any = { id: 3, label: 'Test3' };
let index = currentPickSelection.findIndex(item => {
return item.id == droppedChannel.id; //use unique value instead of item object
});
if (index > -1)
currentPickSelection.splice(index, 1, draggedChannel);

Angular 2 accessing value in an array

Component:
import { Component, OnInit } from '#angular/core';
import * as _ from "lodash";
import { AF } from '../angularfire.service';
#Component({
selector: 'app-record-chart',
templateUrl: './record-chart.component.html',
styleUrls: ['./record-chart.component.less']
})
export class RecordChartComponent implements OnInit {
currentUser = [];
userRecords = [];
topRecords = [];
topRecordLabels = [];
movements = [
"Back Squat",
"Bench Press",
"Clean",
"Clean & Jerk",
"Deadlift",
"Front Squat",
"Jerk",
"Power Clean",
"Power Snatch",
"Push Press",
"Snatch",
"Strict Press"
];
public barChartOptions:any = {
scaleShowVerticalLines: false,
responsive: true
};
public barChartLabels = this.topRecords[0];
public barChartType:string = 'bar';
public barChartLegend:boolean = true;
public barChartData:any[] = [
{data: [65, 59, 80, 81, 56, 55, 40], label: 'Series A'},
{data: [28, 48, 40, 19, 86, 27, 90], label: 'Series B'}
];
// events
public chartClicked(e:any):void {
console.log(e);
}
public chartHovered(e:any):void {
console.log(e);
}
constructor(private afService: AF) {
// Get current user details.
afService.getCurrentUserInfo().then(currentUserDetails => {
this.currentUser.push(currentUserDetails);
}).then(() => {
// Populate lifts array
for(let movement of this.movements) {
this.afService.getRecords(movement, this.currentUser[0].userID).subscribe((data) => {
var sortedArray = _.orderBy(data, ['weight']);
var sortedArray2 = _.uniqBy(sortedArray,'weight');
// console.log(sortedArray2);
this.userRecords.push(sortedArray);
var newRecords = sortedArray
.filter(function(record) {
return sortedArray.find(function(innerRecord) {
return innerRecord.name === record.name && innerRecord.weight > record.weight; }) === undefined;
});
for (let record of newRecords) {
this.topRecords.push(record);
}
});
}
}).then(() => {
// console.log(this.topRecords);
for (item in this.topRecords) {
this.topRecordLabels.push(item.movement);
}
console.log(this.topRecords);
})
}
ngOnInit() {
}
}
this.topRecords Array output:
How do I iterate through every object in this array and push all of the movement values into their own array? I thought I would be able to access them individually with this.topRecords[0] in a for loop, but it always returns a length of 0.
This is what I thought would work:
for (item in this.topRecords) {
this.topRecordLabels.push(item.movement);
}
But it makes 0 iterations. I'm stuck on figuring out how to access and cycle through the objects of this array.
You can iterate through the array with the map operator and then return another array for your field like this:
this.topRecordLabels = this.topRecords.map((item)=> item.movement);
Example usage: https://jsfiddle.net/echonax/n0e0qxng/
Please remove this line first :
public barChartLabels = this.topRecords[0];
This doesn't make nay sense.
You need to read the differnce b/w for in and for of
Replace your code with :
for (let item of this.topRecords) {
this.topRecordLabels.push(item.movement);
}
For more information , please checkout the link :
What is the difference between ( for... in ) and ( for... of ) in javascript?
#echonax figured this out:
this.topRecordLabels = this.topRecords.map((item)=> item.movement)

Resources