简体   繁体   中英

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?

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)

probably, you need to check first:

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

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) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM