We help IT Professionals succeed at work.
Private
Troubleshooting Question

Push object into array

37 Views
Last Modified: 2020-11-18
Hello there,

I get array of JSON Objects from server and need to make some adjustments on my client side to fill its data in the form. I have problem filling the array and i get this error
ERROR TypeError: Cannot read property 'push' of undefined
Below is my code,

console.log("this.product "+JSON.stringify(this.product));
console.log("this.product "+JSON.stringify(this.product[0].quantity));
console.log("this.product "+JSON.stringify(this.product[0].rawmaterialid));

this.product.rawmaterialwh.push({'rawmaterialid':this.product[0].rawmaterialid,'qty':this.product[0].quantity});
    console.log("this.products ",this.product.rawmaterialwh);
    // Update the data on the form
    this.form.patchValue({

      entrydate: this.product[0].dateofentry,
      receiptno: this.product[0].receiptno,
      supplier: this.product[0].supplier,
      warehouse: 1,
    });

 this.form.setControl('rawmaterialwh', this.fb.array(this.product.rawmaterialwh || []));


Below is the data I get from the server and I am trying to adjust it
[{"id":72,"receiptno":"908","dateofentry":20200819,"supplier":10,"rawmaterialid":14,"quantity":20},{"id":72,"receiptno":"908","dateofentry":20200819,"supplier":10,"rawmaterialid":11,"quantity":80}]

My form data has to be in this format
class rawmaterialWH {
  rawmaterialid: number;
  qty: number
}

export interface WarehouseEntry{
  id?: number;
  entrydate: number
  receiptno:string
  warehouse:number
  supplier:number
  rawmaterialwh: Array<rawmaterialWH>
}

I need to get each of them 
"rawmaterialid":14,"quantity":20
from the Array of JSON and push them in the 
rawmaterialwh
like so, but I get this error
this.product.rawmaterialwh.push({'rawmaterialid':this.product[0].rawmaterialid,'qty':this.product[0].quantity});
Comment
Watch Question

Author

Commented:
I also tried creating an object of rawmaterialWH and passing to the 
this.product.rawmaterialwh
But still I get this push error, Below is my tried code

this.rawmaterialWH.rawmaterialid = this.product[0].rawmaterialid;
this.rawmaterialWH.qty = this.product[0].quantity;
console.log("this.products ",this.rawmaterialWH);
this.product.rawmaterialwh.push(this.rawmaterialWH);



HainKurtSr. System Analyst
CERTIFIED EXPERT

Commented:
use

this.product.rawmaterialwh = {
  'rawmaterialid': this.product[0].rawmaterialid,
  'qty': this.product[0].quantity
}
HainKurtSr. System Analyst
CERTIFIED EXPERT

Commented:
I guess you will remove old properties as well...
https://jsfiddle.net/HainKurt/zLheq3jf/

product.forEach(element => {
  element.rawmaterialwh = {
    'rawmaterialid': element.rawmaterialid,
    'qty': element.quantity
  }
  delete element.rawmaterialid;
  delete element.quantity;
});

console.log("this.product AFTER ", this.product);

Michel PlungjanIT Expert
CERTIFIED EXPERT
Top Expert 2009

Commented:
I would expect this would work for you

https://jsfiddle.net/mplungjan/gvp9cazy/

const rawmaterialwh = objFromJSON.map(({rawmaterialid,quantity}) => ({rawmaterialid,quantity}))

Open in new window

Author

Commented:
Thanks for your comments. When i add that code,I get this error.



Author

Commented:
Thanks for your comment.

What is obj

Michel PlungjanIT Expert
CERTIFIED EXPERT
Top Expert 2009

Commented:
Sorry. obj is the object from JSON containing the

 [{
  "id": 72,
  "receiptno": "908",
  "dateofentry": 20200819,
  "supplier": 10,
  "rawmaterialid": 14,
  "quantity": 20
}, {
  "id": 72,
  "receiptno": "908",
  "dateofentry": 20200819,
  "supplier": 10,
  "rawmaterialid": 11,
  "quantity": 80
}]

Open in new window

Author

Commented:
I tried that but i get error

Author

Commented:
Here is the full method code and I have attached screno shot of my console to see the flow
getSupplierToCompanyDetailsByID(id: number): void {
    console.log("Inside getSupplierToCompanyDetailsByID() " +id);
    this.sendtoCompanyFromService.getSupplierToCompanyDetailsByID(id)
      .subscribe({
        next: (product: WarehouseEntryFromSupplierToCompany) => {
          console.log("response: "+ JSON.stringify(product));

          this.displayProduct(product)
        },
        error: err => this.errorMessage = err
      });
  }


displayProduct(product: WarehouseEntryFromSupplierToCompany): void {
    if (this.form) {
      this.form.reset();
    }
    this.product = product;

    if (this.product.id === 0) {
      this.isNew = true;
      console.log("isNew id "+this.isNew)
    } else {
      this.isNew = false;
      console.log("isNew id "+this.isNew)
    }

    console.log("this.product "+JSON.stringify(this.product));
    console.log("this.product "+JSON.stringify(this.product[0].quantity));
    console.log("this.product "+JSON.stringify(this.product[0].rawmaterialid));
    //this.product.rawmaterialwh.push({'rawmaterialid':this.product[0].rawmaterialid,'qty':this.product[0].quantity});

    const rawmaterialwh = this.product.map(({rawmaterialid,quantity}) => ({rawmaterialid,quantity}))

    // Update the data on the form
    this.form.patchValue({

      entrydate: this.product[0].dateofentry,
      receiptno: this.product[0].receiptno,
      supplier: this.product[0].supplier,
      warehouse: 1,
    });

    this.form.setControl('rawmaterialwh', this.fb.array(this.product.rawmaterialwh || []));
  }



Author

Commented:
HainKurt 

I was able to run the code even with that error on the foreach and below is my output. But still I dont see any data in the rawmaterialwh array in my form, any idea.





Author

Commented:
I think the issue is the rawmaterialwh is not in array format but is object and that is why it is not showing up.

this output

this.product AFTER {"id":74,"receiptno":"5555","dateofentry":13990828,"supplier":8,"rawmaterialwh":{"rawmaterialid":17,"qty":25}}
should become like so

{"id":74,"receiptno":"5555","dateofentry":13990828,"supplier":8,"rawmaterialwh":[{"rawmaterialid":17,"qty":25}]}
Michel PlungjanIT Expert
CERTIFIED EXPERT
Top Expert 2009
Ok forget my code

Author

Commented:
Ok forget my code 
what do you mean??
Michel PlungjanIT Expert
CERTIFIED EXPERT
Top Expert 2009
HainKurt had the right idea to remove stuff from the object after saving the array

Author

Commented:

Author

Commented:
>>HainKurt had the right idea to remove stuff from the object after saving the array 
yes only that it needs to be in array format. as I have showm above
CERTIFIED EXPERT
Most Valuable Expert 2018
Distinguished Expert 2019
The issue you have is that in your products variable, you have an array of products - each product has a rawmaterialid and qty. You only need one of those products, but with a property containing all of the rawmaterialids and qtys. Here's a quick example:

let materials = []

product.forEach((prod) => {
    materials.push({
        materialId : prod.rawmaterialid,
        qty : prod.quantity
    })
})

let newProd = {
    id : product[0].id,
    receiptno : product[0].receiptno,
    dateofentry : product[0].dateofentry,
    supplierid : product[0].supplierid,
    rawmaterialwh : materials,
}

console.log(newProd)

Open in new window

IT Expert
CERTIFIED EXPERT
Top Expert 2009
This problem has been solved!
(Unlock this solution with a 7-day Free Trial)
UNLOCK SOLUTION
Michel PlungjanIT Expert
CERTIFIED EXPERT
Top Expert 2009
I read this to mean there is something that should have

rawmaterialid: 14

but it is not found. I cannot help you there since that is something not visible in the code you have shown so far.
Michel PlungjanIT Expert
CERTIFIED EXPERT
Top Expert 2009
I have no angular experience, sorry

Author

Commented:
no worries,thanks for your help!! 

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions