As shown below, I am seeing [init, init]
when I view a collection of objects in the console. In order to access the properties directly, I have to stringify each item and then parse them back to an object, which seems silly. Is there a better way to do this?
By copying the properties on the instance into a new object, eg { ...init }
, you'll have a new plain object that doesn't inherit from Init.prototype
:
// Look at results in browser console, not snippet console:
class Init {
constructor() {
this.item = 'item';
}
}
// Your original situation:
const arrOfInits = [new Init(), new Init()];
console.log(arrOfInits);
// Assign all properties on instance to standard object:
const arrOfObjects = arrOfInits.map(init => ({ ...init }));
console.log(arrOfObjects);
Still, you should still be able to access properties on init
instances without any special code:
// Look at results in browser console, not snippet console:
class Init {
constructor() {
this.item = 'item';
}
}
// Your original situation:
const arrOfInits = [new Init(), new Init()];
console.log(arrOfInits[0].item);