successdav's avatar

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;
                }
            },
0 likes
6 replies
bobbybouwmann's avatar

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.

1 like
successdav's avatar

Yes it is an array and after trying this out on the console, I release its actually working but vue doesn't pickup on the new data that was added using this method

this.itemsTwo['root'] = item;

but when I use .push

this.itemsTwo.push(item)

Vue notice add the new item to the array.

The problem with .push is when the key is not define, it hits an error on the console

successdav's avatar

Can you please give me a little explanation?

The thing here is, there is not key 'root' on the object 'items', so I want to define this key and assign it with a value

jbloomstrom's avatar

You have to take special care when dealing with arrays to make them reactive. Check out this page for more info.

When you modify an Array by directly setting an index (e.g. arr[0] = val) or modifying its length property [Vue.js] cannot pickup these changes. Always modify arrays by using an Array instance method, or replacing it entirely. Vue provides a convenience method arr.$set(index, value) which is syntax sugar for arr.splice(index, 1, value).

Further reading: Reactivity in Depth and Array Change Detection.

1 like
successdav's avatar

Thank you for that information, now this explains why the code isn't working:

The target object cannot be a Vue instance, or the root data object of a Vue instance.

But why is this code too not working

if (this.items.hasOwnProperty(data.parent_id)) {
                        this.items[data.parent_id].push(data)
                    }else {
                        let newItems = this.items;
                        this.items = [];

                        newItems[data.parent_id] = [data];

                        this.items = newItems;
                    }

If the items has the key define, the push statement works and if it doesn't have the key define, the else statement does update the Items array and checking it on the vue dev tool, the data shows up there but the content on the browser doesn't change

Can you please help?

Please or to participate in this conversation.