Initialise an object with array properties

Tags: , , ,



How can I initialise an object in JavaScript, the properties of which would be arrays?

I want to have an object of this format:

foo = { prop1: [0, 1], prop2: [1, 1], prop3: [0] }

My usecase is the following:

– When a property does not exist, create this property which should be an array and add a number.

– When a property exists already, push the number to that array; this way I cannot initialise an array every time.

What I’ve done so far is this:

  var obj = {};
  arr.forEach(x => { !obj[x] && obj[x].push(1) });

I am getting this error:

Uncaught TypeError: Cannot read property ‘push’ of undefined

which makes sense, as the property has not been initialised as an empty array.

Answer

Add this snippet:

arr.forEach((x) => {obj[x] = (obj[x] || []).concat(1);})

If obj[x] is undefined, then it hasn’t been initialized. Therefore, undefined || [] resolves to [], an empty array, to which 1, or whatever data you want, can be concatenated.



Source: stackoverflow