Vue automatically populates an empty array with an Observer object

I have been attempting to create an empty array in the data and then fetch a JSON from the server to populate it.

The issue I am encountering is that the array consistently includes an extra Observer object, so when I log it, I see:

empty items array: [ob: Observer]

Below is a snippet of the code:

data() {
        return {
            items: []
        }
    },
 created() {
         this.$http.get('/api/menus').then(function (response) {

            console.log('items before', this.items); //THIS LOGS items before: [__ob__: Observer]
             this.items = [].concat(response.body);
            this.items.forEach(function (item) {
              console.log('item', item);

              item.$add('active', false);

              item.tests.forEach(function (test) {
                  test.$add('active', false);
              });
        });

         }).catch(function (err) {
             console.error('err', err);

         });

     },

The problem arises when attempting to add a new property to objects in the array, resulting in an error:

err TypeError: item.$add is not a function

Upon debugging, I noticed this occurs because it considers the observer object as part of the array.

Is this behavior normal? Should I simply check if $add exists? Furthermore, how does Vue handle rendering this object in the view?

Answer №1

If you need to change the active property in your items object to false, as well as set all instances of the active property in the tests property of each item to false, you can follow these steps.

Vue.js is reactive and automatically detects changes, but this applies mainly to objects themselves rather than their properties. When dealing with arrays, Vue only notices changes made by certain methods (learn more about list rendering in Vue.js here):

  • push()
  • pop()
  • shift()
  • unshift()
  • splice()
  • sort()
  • reverse()

What about properties? To ensure that Vue recognizes changes deep within an array or object, you can use Vue.set(object, property, value) or this.$set within any Vue instance.

In your scenario, you can implement the solution as shown below:

this.items.forEach(function (item, key) {
    console.log('item', item);

    this.$set(this.items[key], 'active', false);

    item.tests.forEach(function (test, testKey) {
        this.$set(this.items[key].tests[testKey], 'active', false);
    }, this);
}, this);

This implementation should resolve the issue. For a functional example, refer to: http://jsbin.com/cegafiqeyi/edit?html,js,output (note the utilization of some ES6 features).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Show the "Splash" picture, then switch to a newly uploaded image and show it for a set amount of time

I am in the process of developing an HTML/JavaScript page that will showcase a splash image (splash.jpg) until it gets replaced by another image file called latest.jpg. Once this latest.jpg is displayed, I want it to remain on the screen for 90 seconds bef ...

What is the best way to retrieve the js window object within emscripten's EM_JS function?

I'm looking to access the window.location in an EM_JS method in order to call a JavaScript method from C++. My attempted approach was: EM_JS(const char*, getlocation, (), { let location = window.location; let length = lengthBytesUTF8(location ...

Ways to dynamically update the value of an object property within reactJS state

In the scenario where a component holds state like so: this.state = { enabled: { one: false, two: false, three: false } } What is the proper way to utilize this.setState() in order to set the value of a dynamic property? An attempt such ...

JavaScript query-string encoding

Can someone clarify why encodeURI and encodeURIComponent encode spaces as hex values, while other encodings use the plus sign? I must be overlooking something. Appreciate any insights! ...

Inadequate termination of the while loop

I'm trying to generate a line of text in JavaScript running in Node, ensuring that it does not exceed a certain number of syllables. To achieve this, I have created a function utilizing the "syllable" library as follows: function generateLine(maxSyll ...

Choose children input textboxes based on the parent class during the onFocus and onBlur events

How can I dynamically add and remove the "invalid-class" in my iti class div based on focus events in an input textbox, utilizing jQuery? <div class="form-group col-md-6"> <div class="d-flex position-relative"> & ...

"Learn how to use jQuery to transform text into italics for added

Within my ajax function, I am appending the following text: $('#description').append("<i>Comment written by</i>" + user_description + " " + now.getHours() + ":" + minutes + ">>" + description2+'\n'); I am intere ...

No result returned by IntersectObjects function

Recently, I've been delving into the world of three.js to determine if a ray intersects with an object. My scene is all set up and looking great! I tried clicking on the sphere that I created using the following code: var intersected_objects = []; ...

What is the best way to utilize a single Google Map component instance across multiple children?

Seeking a method to maintain the same Google Map instance throughout my entire app, as each map load incurs charges... Currently utilizing google-map-react. An instance of a new Map is created in ComponentDidMount, suggesting that it's important to k ...

What is the best way to delete rows from an HTML table?

I am trying to update the table, but every time the setInterval function is triggered, the append method adds the same rows again. I want the old rows to be removed before inserting the new ones. $(document).ready(function() { function updateT ...

JQuery cannot target content that is dynamically inserted through an Ajax request

When I use an ajax call to pass dynamically generated html, such as in the example below: var loadContent = function(){ $.ajax({ url: '/url', method: 'GET' }).success(function (html) { $('.con ...

Calculate the total sum of input values using jQuery

Here is the HTML I've been working with: I am trying to create a script where one textbox will display the total amount, and another textbox will display the following data: "name": [{ "id": 3, "qty": 2 }, { "id": 4, "qty": 5 }] Here's ...

When the component mounts in React using firestore and Redux, the onClick event is triggered instantly

I am facing an issue with my component that displays projects. Each project has a delete button, but for some reason, all delete buttons are being automatically triggered. I am using Redux and Firestore in my application. This behavior might be related to ...

Injecting multiple instances of an abstract service in Angular can be achieved using the following techniques

I am fairly new to Angular and currently trying to make sense of the code written by a more experienced developer. Please excuse me if I'm not adhering to the standard communication practices and vocabulary. There is an abstract class called abstract ...

Guide on importing a client-side script using browserify with module.exports exposed through jadeify

I've successfully created a JavaScript file using a Jade template with the help of browserify, browserify-middleware, and jadeify on the server side in Node. The only thing required to generate the JavaScript file is: app.use('/templates', ...

I possess a JSON object retrieved from Drafter, and my sole interest lies in extracting the schema from it

Working with node to utilize drafter for generating a json schema for an application brings about too much unnecessary output from drafter. The generated json is extensive, but I only require a small portion of it. Here is the full output: { "element": ...

Ways to get a Discord bot to echo a message?

As a novice in the world of discord.js and bot creation, I am eager to implement a simple magic 8-ball inspired command. This command will allow users to ask the bot a question and receive a random answer in response. const commands = [ new SlashCommandBui ...

Unable to retrieve $scope.property using direct access, however it is visible when printed to the console using console.log($

I have successfully populated $scope with data using a get call: httpGetAsync("myUrlWasHere", getBlogPosts, $scope); The console outputs the data when I print console.log($scope): https://i.sstatic.net/SkDl9.png However, when I try to access it using c ...

Is there a way to reverse the confirmation of a sweet alert?

Hey there, I'm currently using Sweet Alert to remove a product from my website. I want to implement it with two options - 'ok' and 'cancel'. However, I'm facing an issue where clicking anywhere on the page removes the product ...

Show picture in web browser without the file extension

Is there a way to display an image in the browser without the file extension, similar to how Google and Unsplash do it? For example: Or like this: ...