0

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.

2
  • 2
    can you give us some examples for input and desired output? Commented Aug 14, 2020 at 19:38
  • For example, I am iterating over two arrays, I want to have 0/1 (or true/false) if the arrays include some specific items, e.g. array1 = ["cat", "dog"], array2 = ["dog", "mouse"]; the object would be of this format: { "cat": [1, 0], "dog": [1, 1], "mouse": [0,1] } Commented Aug 14, 2020 at 19:49

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This is elegant :)
Thanks! Javascript's lazy || operator can be very useful. It's often used in functions with optional parameters, to replace undefined with a default value.
1

Ciao you could try this:

let obj = {};
let arr = ["prop1","prop2","prop1","prop3"];
arr.forEach((x) => {
   if(obj.hasOwnProperty(x)) obj[x].push(1);
   else {
      obj[x] = [];
      obj[x].push(1);
   } 
})
console.log(obj);

if obj has already property x (hasOwnProperty) push value 1 else init x as array property and push 1.

1 Comment

Thank you, this is also a nice solution!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.