2

I want to pass an object to an array with the following Class and methods:

class PieData {
  constructor(data = [], name, y) {
    this.data = data;
    this.name = name;
    this.y = y;
  }
  addData() {
    this.data.push({
      name: this.name,
      y: this.y
    });
  }
}

const browsers = new PieData();

browsers.addData("Chrome", 25);
browsers.addData("Firefox", 30);

console.log(browsers);

The data should look like this:

let data = [
  {
 name: "Chrome",
 y: 61.41
   },
   {
 name: "Internet Explorer",
 y: 11.84
   }
]

Can anyone help me how to do this? This results in undefined :-(. I´m pretty new to programming. I think I do not really understand the "this" keyword.

3
  • 1
    You call browsers.addData("Chrome", 25); but that method doesn't take any parameters Commented Oct 28, 2019 at 19:19
  • Also, the constructor takes parameters but you never supply any. I find it hard to understand what the intent here is - is "Chrome" supposed to be the name put into the this.data array, or is it supposed to be the name of the object? Or something different? Commented Oct 28, 2019 at 19:21
  • The method should create an object like in the example data and be stored in the empty data array Commented Oct 28, 2019 at 19:24

2 Answers 2

4

Instead to add values on constructor you must send the values into addData function

class PieData {
    constructor() {
        this.data = [];
    }
    addData(name, y) {
       this.data.push({ name, y });
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Try to declare variable and use them in function:

class PieData {
    constructor(data = [], name, y) {
      this.data = data;
      this.name = name;
      this.y = y;
    }

    addData(name, y) {
        this.data.push({ name: name, y: y });
    }
 }



const browsers = new PieData([], 'test', 'y variable');

browsers.addData("Chrome", 25);
browsers.addData("Firefox", 30);

console.log(browsers);

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.