ang
ang

Reputation: 1581

How to push to an array index that does not yet exist

I am trying to create objects sets in an array, and create a new set if the item does not yet exist.

The data structure is like

[
  {
    "order": orderData,
    "items": itemData
  }, {
    "order": orderData,
    "items": itemData
  }
]

However, when trying to create a new array index on-the-fly and push to it, I get the following error:

Cannot set property 'items' of undefined

In this case, setNo = 2, but this.cart[2] is not yet instantiated.

this.cart[setNo]['items'].push(items);

How do I initialize this index so that it can be pushed to on-the-fly?

Upvotes: 0

Views: 77

Answers (3)

Akrion
Akrion

Reputation: 18515

You could also use the ternary operator to check and add as well:

let arr = [
  { "order": {}, "items": [] }, 
  { "order": {}, "items": [] }
], setNo = 2

arr[setNo] 
  ? arr[setNo]['items'].push(1) 
  : (arr[setNo] = { order: {}, items: [] })['items'].push(1)
	
console.log(arr)

Upvotes: 0

Serhiy
Serhiy

Reputation: 369

probably, you need to check first:

if (!this.cart[setNo]) {
   this.cart[setNo] = {order: {}, items: []};
} 
this.cart[setNo]['items'].push(item);

Upvotes: 1

Maheer Ali
Maheer Ali

Reputation: 36564

You can check if the cart[setNo] doesn't exist set it object with items property

if(!this.cart[setNo]) cart[setNo] = {items:[]};
this.cart[setNo]['items'].push(items)

Upvotes: 1

Related Questions