Is there a way to initialize an object in JavaScript with properties that are arrays?
I am looking to create an object structured like this:
foo = { prop1: [0, 1], prop2: [1, 1], prop3: [0] }
My scenario is as follows:
- If a property doesn't exist, I want to create it as an array and add a number.
- If a property already exists, I need to push the number to that existing array without reinitializing it every time.
This is what I have attempted so far:
var obj = {};
arr.forEach(x => { !obj[x] && obj[x].push(1) });
However, I keep encountering this error:
Uncaught TypeError: Cannot read property 'push' of undefined
This error occurs because the property has not been initialized as an empty array beforehand.