rcarcia02
rcarcia02

Reputation: 967

ERROR TypeError: .forEach is not a function

In my Angular program, I need to create a deep copy of my object so that I'll be able to compare the changes. Here is what I tried and I get an error in my console that says ERROR TypeError: .forEach is not a function. How do I fix this?

import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';

import { PTOData } from './pto-data';
import { PTODataService } from './pto-data.service';
import { EmpInfo } from './emp-info';
import { EmpInfoService } from './emp-info.service';

@Component({
    selector: '[pto-row-edit]',
    templateUrl: `./row-edit.component.html`,
    styleUrls: ['./row-edit.component.css']
})

export class RowEditComponent implements OnInit {

    // Inputs & Outputs to/from grid component
    @Input() pto: PTOData[];
    @Input() rowSelected: number;

    @Output() onDelete = new EventEmitter<number>();
    @Output() onSave = new EventEmitter<number>();

    opto: PTOData[];

    private initialized: boolean = false;

    ngOnInit(): void {
        this.opto = [];
        this.pto.forEach(x => this.opto.push(x))
        console.log(this.opto);
    }

    constructor(
        private ptodataService: PTODataService,
        private empInfoService: EmpInfoService) { }

    resetRow(pto: PTOData): void {
        console.log(this.pto);
        console.log(this.opto);
        this.rowSelected = null;
        this.onSave.emit(this.rowSelected);
    }

}

Upvotes: 2

Views: 3337

Answers (1)

Mike Hill
Mike Hill

Reputation: 3772

See comments on the original question. The original issue, as @SaxyPandaBear pointed out, was that an array value was expected for the @Input() pto field rather than a plain object, so the declared type needed to be changed and the array-cloning statement needed to be replaced with an object-cloning statement.


If you want to clone an object instead of an array, use:

this.opto = Object.assign({}, originalObject);

or (my preferred method, since it has better TypeScript type-checking support) the spread operator:

this.opto = {...originalObject};

Upvotes: 1

Related Questions