How to edit values of an object inside an array in a class - JavaScript?

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

For this, use the “this” keyword.

Example

Following is the code −

class Employee {
    constructor() {
        this.tempObject = [
            {
                firstName: "David",
                setTheAnotherFirstName() {
                    this.firstName = "Carol";
                },
            },
        ];
    }
} 
var empObject = new Employee(); 
empObject.tempObject[0].setTheAnotherFirstName(); 
console.log("The Change First Name is=" + empObject.tempObject[0].firstName);

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo220.js.

Output

The output is as follows −

PS C:\Users\Amit\JavaScript-code> node demo220.js
The Change First Name is=Carol
raja
Published on 03-Oct-2020 17:38:19
Advertisements