Reorganizing a Multidimensional Object in JavaScript After Removing a Nested Object

I am facing an issue with deleting a nested object based on index and i in Vuejs methods. The current code is not working as expected, as it deletes multiple objects instead of just the one specified. Additionally, sometimes the indexing is incorrect but I haven't been able to identify the cause of this yet. Any help or suggestions on how to fix this buggy code would be greatly appreciated.

Edit: I am using an npm package for searchable multi-select selection lists that only allow objects to be passed to the options attribute.

Below is the script:

export default {
props: {
  tag_filters: Object
},
data() {
   return {
     tagfilters: {
                0: {
                    0: {
                        code: {
                            code: 'Thank You Codes'
                        },
                        condition: {
                            condition: 'AND'
                        }
                    },

                }
            }
       }
}
computed: {
  realTagFilters() {
                if (Object.keys(this.tag_filters).length > 0 && typeof Object.keys(this.tag_filters) !== 'undefined') {
                    return this.tag_filters['filter'];
                } else {
                    return this.tagfilters;
                }
            }
},
method: {
       deleteFilter(index, i){
                delete this.realTagFilters[index][i];
                for(var property in this.realTagFilters) {
                    for (var p in this.realTagFilters[property]) {
                        if(property > index && p > i) {
                            property -= 1;
                            this.realTagFilters[property] = this.realTagFilters[property + 1];
                            delete this.realTagFilters[property + 1];
                            if(p > i) {
                                p -= 1;
                                this.realTagFilters[property][p] = this.realTagFilters[property][p + 1];
                                delete this.realTagFilters[property][p + 1];
                            }
                        }
                        else if (property == index && p > i) {
                            p -= 1;
                            this.realTagFilters[property][p] = this.realTagFilters[property][p + 1];
                            delete this.realTagFilters[property][p + 1];
                        }
                    }
                }
                if(Object.keys(this.realTagFilters[index]).length == 0) {
                    delete this.realTagFilters[index];
                }
                this.$forceUpdate();
            },
}
}

Answer №1

If you're looking to enhance your code, consider using Vue's delete function instead of the traditional javascript delete keyword. For example, replace

delete this.realTagFilters[index][i]
with:

this.$delete(this.realTagFilters[index], i);

An additional tip to notify Vue of data changes is to swap out your object with a new one like this:

// Once your operations are complete:
this.realTagFilters = {...this.realTagFilters};

If necessary, you can always resort to this.$forceUpdate(), an option that you seem to be utilizing already.

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

After redirection to a new page, the Ionic-vue menu malfunctioned

I have developed a reusable header component named Header, which contains an IonMenu component for consistency across pages. The menu is associated with the IonRouterOutlet as per the documentation, but I am encountering an issue when navigating between pa ...

Organize array by "categories" in Javascript and preserve the original sequence

There is a dataset presented below: [ { "name": "Item1", "section": "section1", "total": 3, }, { "name": "Item1", "section": "section2", "total": 4, }{ "name": "Item1", "section": "section3", "total": 7, }, { "name" ...

The 'in' operator cannot be utilized to search for '_id' within

I am attempting to retrieve an existing user document using mongoose with express, but I am encountering the following error: /webroot/api.domain.com/production/node_modules/mongoose/lib/document.js:162 if (obj && '_id' in obj) con ...

What are the steps to increase or decrease the quantity of a product?

Is there a way to adjust the quantity of products in the shopping cart? I would like to be able to increase and decrease the quantity, while also displaying the current value in a span tag. <a href="javascript:" id="minus2" onclick="decrementValue()" ...

Could a commenting feature be seamlessly integrated directly into the video player, accessible with a simple click?

I'm exploring the idea of developing a video player that allows users to add comments directly from the player itself. Imagine this: the typical toolbar at the bottom includes standard features like seek bar, volume control, play/pause buttons, but wi ...

Implementing dynamic watchfile listeners in Node.js upon client connection and appropriately removing them thereafter

Currently, during a client connection event, a file is being watched. However, when a second client connects, the same file is watched again using fs.watchFile(). Upon a client disconnecting event, the file is unwatched using fs.unwatchFile(). This means ...

The success callback function in jQuery.ajax() sometimes receives undefined parameters

In my current code, I am using an ajax call to communicate with a Wordpress file responsible for creating WP users. jQuery.ajax({ method: 'POST', dataType: 'json', url: ajax_object.ajax_url, // Post ...

Displaying a list in Angular 2/4 without keeping track of any modifications

Is there a way to display a list of strings without tracking changes? (I'm experiencing performance issues). Fetching a list of languages from a REST API and then dynamically generating dropdowns for each language using *ngFor is causing the app to s ...

Ways to implement a resize function in Angular JS without relying on the document and window objects

Is there a way to convert the following jQuery code into Angular JS without relying on Document and Window? Can we write the code without utilizing Document.ready and window? ...

Utilize AngularJS to inject a value into the jk-rating-stars element

Hello there, I'm wondering how to assign a value to "rating" attribute as "ctrl.rating" using $scope in AngularJS. <jk-rating-stars max-rating="5" rating="ctrl.rating" read-only="ctrl.readOnly" on-rating="ctrl.onRating(rating)"> </jk-rat ...

Unable to associate ngModel because it is not recognized as a valid property of the "Component"

Currently, I am in the process of creating a custom form component using Angular 4. I have included all necessary components for ngModel to function properly, but unfortunately, it is not working as expected. Below is an example of my child component: ex ...

Creating an interactive Table of Contents in Sharepoint using only JavaScript

Imagine you have a massive Sharepoint wiki page filled with various heading tags like H1, H2, H3, and H4 - now picture creating a dynamic Table of Contents using these tags. The goal is to categorize these tags by group and utilize the HTML <detail> ...

Maintain Bullet and Arrow Size with JSSOR Scaling Feature

I am currently utilizing the jssor image slider with jquery and overall, it is functioning well. However, I have encountered an issue when attempting to resize the slider. My goal is to dynamically resize the slider whenever the window width changes. The ...

Generate an HTML document from a website page

Having difficulty grasping this concept. I am completely lost on where to begin. It is imperative that I determine how my website can generate a file (whether it be HTML or Text format) and enable users to download it, similar to the functionality in Goo ...

Encounter a 400 status code error while utilizing AZURE ML with nodejs

I encountered an issue while attempting to consume the web service, receiving the error message: The request failed with status code: 400 {"error": {"code":"BadArgument","message":"Invalid argument provided.", "details":[{"code":"BatchJobInputsNotSpecif ...

Assigning a click event to an element within CKEditor

Looking to add a click event to an element in ckeditor4-angular for custom functionality <div class="fractional-block" id="fractional-block"><span>5</span><svg height="5" width="100%"><line ...

Incorporating angularjs within a page loaded with jquery.load

Currently, I am in the process of developing a web application designed to cater to multi-device applications. The foundation of this project involves a framework built using nodejs, socket.io, and express which manages the distribution of views. This fra ...

Exploring the world of JSON files using JavaScript

Basically, my bot responds to a command (!accounts) by providing users with information based on their ID. For example, if an ID of 662 sends the command !account, the bot will search for steamID 662 in the json files and display the currency and correspon ...

The error message states: `discord.js TypeError: Unable to access the property 'resolve' as it is undefined`

Encountering an issue with the following code snippet const Discord = require('discord.js'); module.exports = { name: 'info', description: "Shows BOT's Informations", execute(message, client, args) { c ...

request.json method will only return a string

I am utilizing Axios and Flask for building RESTful APIs. However, I have encountered an issue with JSON data transmission between Axios and Flask. Despite multiple attempts, I am unable to retrieve JSON data from Axios using request.json. Various troub ...