Remove an element from an array within objects

Need help with removing specific items from an array within objects?

If you want to delete all hobbies related to dancing, you may consider using the splice method

const people = [{
            id: 1,
            documents: [{
                id: 1,
                category: [{
                        hobby: 'soccer'
                    },
                    {
                        hobby: 'dance'
                    }
                ]
            }, {
                id: 2,
                category: [{
                        hobby: 'soccer'
                    },
                    {
                        hobby: 'dance'
                    }
                ]
            }]
        }, {
            id: 2,
            documents: [{
                id: 1,
                category: [{
                        hobby: 'dance'
                    },
                    {
                        hobby: 'soccer'
                    }
                ]
            }, {
                id: 2,
                category: [{
                        hobby: 'soccer'
                    },
                    {
                        hobby: 'dance'
                    }
                ]
            }]
        }];
        
        // Loop through each person
        people.forEach(person => {
            person.documents.forEach(document => {
                document.category.forEach((cat, index) => {
                    if (cat.hobby === 'dance') {
                        // Use splice to remove dance hobby
                        document.category.splice(index, 1);
                    }
                });
            });
        });

        console.log(people);

Answer №1

Although not required, I have found sets to be beneficial for tasks like this:

function removeHobbyFromPeople(people, hobby) {
  people.forEach(person => {
    person.documents.forEach(document => {
      const categoryAsSet = new Set(document.category)
      categoryAsSet.forEach(cat => { 
        if (cat.hobby && cat.hobby === hobby) {
          categoryAsSet.delete(cat)
        }
      })
      document.category = Array.from(categoryAsSet)
    })
  })
}

Normally, I wouldn't convert from an array to a set and back again like in this example, but considering using Set as a data structure instead of an Array could be worth exploring.

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

Using jQuery .animate() leading to erratic input movements

I am currently utilizing jQuery's .animate() feature to create a smooth animation effect on the width of a <div> element when a child <input> is in focus. Nevertheless, I'm encountering an issue where the input field jumps up and down ...

Which framework should be used: client-side or server-side?

I am working on a project similar to craiglist, where users can post announcements for everyday items like cars and flats. I have already developed a significant portion of the backend using a RESTful API in three-tier architecture with Java, connecting to ...

Using checkboxes to filter a list within a ReactiveForm can result in a rendering issue

I have implemented a dynamic form that contains both regular input fields and checkboxes organized in a list. There is also an input field provided to filter the checkbox list. Surprisingly, I found out that when using the dot (.) character in the search f ...

What is the best way to restrict the size of a table that is filled with data from a database?

Currently using a combination of React, Node, Express, and Postgres to populate a table with data retrieved from Postgres. The issue arises when the table becomes overly long, prompting the need to display only 5 rows at once while adding a scroll bar for ...

Exploring the Power of Elasticsearch with Datatables

I'm attempting to utilize functions from an Elasticsearch instance in conjunction with datatables to exhibit results. Currently, I am only able to display 10 results, regardless of the query used. Even though there are 141,000 results in Elasticsearc ...

Error message: "Mismatched data types in Formik errors when utilizing TypeScript"

I have a customized input component for formik which includes an error label if one exists. When I print it like this: {errors[field.name]}, it works. However, {t(errors[field.name]?.toLocaleString())} does not work. import { FieldProps, FormikErrors } ...

Getting around using Material-UI Icons

Is it possible to utilize a Material-UI Icon for navigation using React Router Dom? I attempted the following approach without success: <NavigateBeforeIcon path="/vehicles"></NavigateBeforeIcon> With buttons, I am able to use component={Link ...

Unable to employ Javascript while utilizing AJAX within jQuery Mobile

Exploring the potential of Swiper Javascript Api from within Jquery Mobile raises some challenges. The compatibility issues with Ajax in Jquery Mobile complicate the execution of Javascript functions. This becomes evident when examining example source cod ...

Exploring the differences between React state and CSS :hover in the context of a dropdown menu that is accessible to both desktop users (via mouse) and

I have come across a dilemma regarding a dropdown menu that needs to cater to both Desktop/PC users (with mouse) and Mobile devices (with touch). After considering my options, here are the proposed solutions: OPTION 1 One approach is to implement it usi ...

What is the best way to configure webpack for ng build instead of ng serve?

My .NET web application is hosted in IIS and it also hosts an Angular application. This setup requires both applications to be served on the same port by IIS, primarily because they share the same session cookie. Additionally, they are integral parts of th ...

Tips on incorporating Prisma model into prisma-offset-pagination

I am currently implementing pagination using the prisma-offset-pagination package. To do this, I need to utilize Prisma Model in my code, but I'm unsure of the correct approach: Refer to line: 02 const result = prismaOffsetPagination({ model: user ...

Tips for obtaining the entire date and time on one continuous line without any breaks or separation

Is there a way to retrieve the current date and time in the format of years, months, days, hours, minutes, seconds, and milliseconds like this? 201802281007475001 Currently, I am getting something like: 2018418112252159 This is my code so far: var dat ...

Displaying a JQuery notification when hovering over a link

I am having trouble getting an alert to pop up when I hover over a hyperlink using JQuery and Javascript. The hyperlink is inside an anchor within the main section of the HTML. Any assistance would be much appreciated. Here is my current code snippet: &l ...

Navigational elements, drawers, and flexible designs in Material-UI

I'm working on implementing a rechart in a component, but I've encountered an issue related to a flex tag. This is causing some problems as I don't have enough knowledge about CSS to find a workaround. In my nav style, I have display: flex, ...

Unable to retrieve information using the post method in Express framework

After creating a basic code to fetch data from the client, I am facing an issue where req.body.firstname is showing as undefined. Here is the code snippet: const express = require('express'); const app = express(); const body ...

Why is it not possible to declare an interface or type within a TypeScript class?

I am struggling to define interface | type within a TypeScript class. Here is the code snippet: class MyClass { interface IClass { name: string, id: string } } However, I keep encountering this error: Unexpected token. A constructo ...

Various instances of controllers in Angular.js and JavaScript

I'm facing a challenge with a view that has two identical parts but different content. I want to find a way to use one controller and one view for both the left and right parts. Here's what I currently have in my HTML: <div class="board_bod ...

Angular 2: Utilizing Http Subscribe Method with "this" Context Pointer

Question: http.request('js/app/config/config.json').subscribe(data => { this.url = data.json().url; }); It seems that "this" is pointing to Subscriber instead of the parent class. I was under the impression that the fat- ...

Eliminating an element from an array without the need for iteration

I've been reviewing some documentation, but I have a hunch that there may be a simpler way to eliminate one element from an array without having to utilize an iteration loop. http://jsfiddle.net/G97bt/1/ Check out the updated jsFiddle example: http: ...

Is it possible to have a button within a table that, when clicked, opens a card overlaying the entire table?

I'm having an issue with a table and card setup. When I click the button in the table, the card that appears only covers part of the table. I want it to cover the entire table area based on the content inside the card. How can I make this happen? I&a ...