You need to make sure that this. itemsTwo is actually an array. If it's not an array, you can't assign an array value to it.
Apr 9, 2020
6
Level 4
Set key on an array if it does not exist
Hi! this code doesn't work if the array does not contain the key
this.itemsTwo['root'] = 'hello world';
but if the items array has a property of 'root', it sets the property to 'hello world' and if it does not, it doesn't do anything.
What I am trying to achieve is set the key root on the array items if it doesn't exists on the array but if it does, push this data into it, and here is my code.
add(item) {
if (this.itemsTwo.hasOwnProperty('root')) {
this.itemsTwo['root'].push(item);
}else {
this.itemsTwo['root'] = item;
}
},
Please or to participate in this conversation.