1

I am trying to create an array collection of objects inside a JavaScript class.

class Person {
  object = {};
  employees = new Array();

  constructor() {}

  addPerson(name, age) {
    this.object.name = name;
    this.object.age = age;
    this.employees.push(this.object);
  }

  getGroupInfo() {
    return this.employees;
  }
}

let p1 = new Person();
p1.addPerson("Johnny", 40);
p1.addPerson("Mark", 55);
console.log(p1.getGroupInfo());

The output seems to override with the second input that I am providing.

[ 
  { name: 'Mark', age: 55 }, 
  { name: 'Mark', age: 55 } 
]

I am certainly failing to understand the basic javascript way of class creation :-)

4 Answers 4

2

The second call to addPerson is using a reference of the first this.object and changing the values. You can directly add new objects to the employees array as follows:

class Person {
  employees = new Array();
  constructor() {}

  addPerson(name, age) {
    this.employees.push({name, age});
  }

  getGroupInfo() {
    return this.employees;
  }
}

let p1 = new Person();
p1.addPerson("Johnny", 40);
p1.addPerson("Mark", 55);
console.log(p1.getGroupInfo());

Sign up to request clarification or add additional context in comments.

Comments

1
p1.addPerson("Johnny", 40);
p1.addPerson("Mark", 55);

Both these statements update and work on the same object : this.object which is a property of the p1 instance. The array becomes something like [x,x].

Comments

0

this.object inside Person is same for both. So its value getting overridden

class Person {
  name;
  age;

  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
}

employees = new Array();
let p1 = new Person("Johnny", 40);
let p2 = new Person("Mark", 55);
employees.push(p1);
employees.push(p2);
console.log(employees);

1 Comment

Thanks! but I wanted to specifically create a collection inside the same object.
0

I have accepted the first answer which is correct. One other way I could have implemented it :

class Person {
  employees = new Array();

  constructor() {}

  addPerson(name, age) {
    let object = {};
    object.name = name;
    object.age = age;
    this.employees.push(object);
  }

  getGroupInfo() {
    return this.employees;
  }

 }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.