I want it to be the case that when I instantiate an instance of the class TableCategory, an object is created using the data passed in at instantiation. I want this to happen automatically at instantiation. I don't want have to instantiate the class and then call a method that creates the object. This seems unnecessary cumbersome.
I am using a class because I then want to manipulate the resultant object using getters and setters for multiple instantiations. (In case you wonder why I'm not just using an object in the first place.)
I'm not 100% clear on classes in JS so I'm not sure where I'm going wrong. Please note the object creation is a the product of a function it takes an array passed in at instantiation and an array that is native to the class.
Here's my class:
export class TableCategory {
constructor(categoryValues = []) {
this.categoryValues = categoryValues;
this.categoryKeys = ['alpha','beta','gamma', 'delta'];
this.categoryData = this.categoryKeys.forEach(function(key, i) {
return this.categoryData[key] = this.categoryValues[i];
});
}
}
Then, for example:
const foo = new TableCategory(['a'. 'b', 'c', 'd']);
console.log(foo.categoryData.beta); // b
Perhaps I need to use static ? Not sure, grateful for any help
categoryData(after fixing your code), then why you still need the other two properties? They are easy to get withObject.keys,Object.valuesfrom the third property. You'll have unnecessary overhead to keep those properties synchronised when you start mutating an instance.categoryDatawill have all key/value pairs, but those keys are also incategoryKeys, and the values are also incategoryValues, so you have everything in double. I think you only needcategoryData, as the rest is implied by it. If then you mutate and change a value later, you don't have to change it both incategoryDataand incategoryValues(to avoid inconsistency).