My point in the comments was it seems you're coming at this problem from the wrong direction. Maybe take this approach. Have an array of labels, and array of data, and pass those into the class. You'll still have the array of labels to access (and validate) in your other code, and everything will still work.
const labels = [ 'id', 'name', 'price', 'category', 'stock' ];
const data = [ 1, 'Bob', 100, 2, 1];
class Product {
constructor(labels, data) {
data.forEach((el, i) => this[labels[i]] = el);
}
};
console.log(new Product(labels, data));
console.log(labels);
Or, if your products are identical in terms of properties you could just use an array of them, and use Object.keys
to get the labels of the first object.
const data = [{ id: 1, name: 'Bob', price: 100, category: 2, stock: 1 }];
const labels = Object.keys(data[0]);
class Product {
constructor(data) {
for (let key in data) {
this[key] = data[key];
}
}
};
console.log(new Product(data[0]));
console.log(labels);