Add an array into an object using $set (properties remain unchanged)

I have an object with the following structure:

obj: {
  1: {
    'a': [ [] ],
    'b': [ [] ]
  }
}

Now, I am attempting to append 'c' => [ [] ] to this object in a watcher.

  • My first attempt was using this.obj[1]['c'] = [ [] ], however, it did not watch changes on the props of the child component when done this way. I suspect that I need to use $set.

  • Next, I tried

    this.$set(this.obj, 1, { ['c']: [ [] ] })
    - while this successfully watched the changes, it unfortunately removed the 'a' and 'b' properties entirely.

  • Lastly, I attempted

    this.$set(this.obj[1], ['c'], [ [] ]);
    - this appeared to change the object but still didn't trigger prop watches.

What is the correct way to use $set?

Answer №1

As it has been pointed out in the remarks, you can simply utilize

this.$set(this.obj['1'], 'c', [[]])

By way of illustration...

new Vue({
  el: '#app',
  data: {
    obj: {
      1: {
        'a': [ [] ],
        'b': [ [] ]
      }
    }
  },
  methods: {
    addC: function() {
      this.$set(this.obj['1'], 'c', [[]])
    }
  }
})
<div id="app">
  <p><button @click="addC">Add "c" property</button>
    <ul>
      <li v-for="(prop, key) in obj">
        {{ key }}
        <ul>
          <li v-for="(arr, letter) in prop">
            {{ letter }} - size: {{ arr.length }}
            <ul>
              <li v-for="(sub, idx) in arr">
                Index {{ idx }} - size: {{ sub.length }}
              </li>
            </ul>
          </li>
        </ul>
      </li>
    </ul>
</div>
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="99efecfcd9abb7adb7ab">[email protected]</a>/dist/vue.min.js"></script>

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

Unable to establish successful Ajax connection with PHP function

I'm encountering an issue with submitting a form through ajax and I can't seem to figure it out: Ajax - samepage <script type="text/javascript"> $(document).on('submit','.subscribe',function(e) { $.ajax({ url: &apo ...

Guide on using webpack to import jQuery

When using webpack, is it necessary to install the jquery file from npm, or can I simply require the downloaded file from the jquery website? directory app/ ./assets/javascripts/article/create/base.js ./assets/javascripts/lib/jquery-1.11.1.min.js webpack ...

What is the best way to retrieve a specific item from an array of objects stored in JSON format using React?

I have received a json file named data.json which contains multiple objects in an array. My goal is to extract the value of a specific key from each object. To achieve this, I am utilizing react redux to fetch these values and present them in a table forma ...

What is the best way to determine the location of a specific line within a text file?

I am in the process of developing a logistics management system. My goal is to display a list of intermediary ports between the specified source and destination once the user enters the source port and destination port. However, I am facing some challeng ...

What could be causing the ajax request to not go through?

Check out this function I created that triggers an event when any inputs in an HTML form are changed. Function Snippet: function customEvent(form, element) { var timer; $(element).keyup(function () { clearTimeout(timer); if ($(ele ...

How can you locate the position of identified text on a webpage to accurately place the mouse cursor there?

When browsing a webpage in my web browser (preferably Firefox), I have the ability to search for a specific text "abc" using ctrl+f. Once found, I need to move my mouse cursor to another relative position on the page and click. Unfortunately, the necessar ...

I had hoped to remove just one item, but now the entire database is being erased

I present it in this way <tr v-for="(foodItem, index) in filteredFoodItems"> <td>{{ foodItem.name }}</td> <td>{{ foodItem.price | currency('£') }}</td> <td>{{ foodItem.category }}< ...

Navigating through hidden input fields in Angular by utilizing the tab key

Seeking a method in Angular to navigate hidden inputs using tab functionality. I have several input forms that display only the text when not on focus. Is there a way to select an input and still be able to tab through the other hidden inputs? Any ideas o ...

The delay between initiating a Next JS route by clicking and the corresponding page actually loading

Just launched my website at this link: I am experiencing a delay of up to 2 seconds between clicking the header links and the page loading. The site works fine in development and on localhost, so I'm not sure why there's such a slowdown on the l ...

"Optimize Magellan Sidebar for Mobile Devices by Relocating it to the Bottom of the Page

After spending a week working with Foundation 5 framework, I'm curious if there is a straightforward way to make my magellan sidebar shift to the bottom of the page when viewed on mobile or tablets. <div data-magellan-expedition="fixed"> <di ...

Combining PageObjects with non-angular pages: is it possible?

I am currently working on writing protractor tests for our application. One specific challenge I have encountered is dealing with a non-angular page within an angular page as an iframe. The issue I am facing is that I cannot properly map fields from the n ...

Having trouble generating an HTML table from JSON data using JavaScript

My attempt to generate a table with data from an external .JSON file using JavaScript is not working as expected. Everything worked fine when the data was hardcoded into the .JS file, but once I tried to fetch it externally using "fetch", the details do no ...

Certain rows in the table should maintain a consistent width, while others are allowed to vary

I am dealing with a table containing certain rows Some of these rows are visible, while others are hidden. The visible rows at the start are referred to as: mainTrs. Clicking on a visible row will make all rows with a class matching its id visible. Cli ...

Can anyone recommend a regular expression that would target values ranging from 0.5 to 24?

I'm searching for a regex pattern that can identify numbers within the range of 0.5 to 24, excluding cases like 0,5 or 22,5. The current pattern I'm using is: /^(([0-9]|1[0-9]|2[0-3])([^,])(\.(0|5)))$/ Despite having excluded the comma ,, ...

Unusual JavaScript Bug: Uncaught TypeError - Unable to access property 'url' of null

I encountered a peculiar JavaScript error. The following message appears in the console: Uncaught TypeError: Cannot read property 'url' of null (Line 83) The code on Line 83 looks like this: var image = '<img class="news_image_options ...

What is the code in CodeIgniter to retrieve the string 'Sugar & Jaggery, Salt' using <a>?

Can someone please help me? I am a beginner in CodeIgniter and I am having trouble passing a URL with a string. The controller is not accepting the string as expected. How can I fix this issue? //Below is the HTML code for passing a string value index.ph ...

When modifying the state of an array within a component, certain values may be overwritten and lost in the process

Currently, I'm faced with the challenge of ensuring that a component displays a loading screen until all images have completed loading. This is necessary because there are approximately 25 images that must finish loading before the page can be display ...

What is the best way to combine elements from different arrays to create a comprehensive listing?

My current function successfully pulls data from another source to create a listing. However, the data I require is spread across multiple arrays, causing some items to be returned as "undefined." At the moment, I am only fetching data from the products a ...

I am encountering an issue where the object I am sending with Next.js is appearing as undefined on the receiving page

When transferring data from my question screen to a result screen, I am using an object called footprintsData. Here is the code snippet for sending the data: const footprintsData = { carFootprint: roundedCarFootprint, electricityFootprint: roundedElect ...

Success is returned as AJAX error

My AJAX call is returning an error as Success instead of a JSON error from ASP.NET MVC. Can someone please advise on how I can resolve this issue? Thank you. [HttpPost] public JsonResult Register(int EventID) { try { ...