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

Sending a POST request in Angular5 using the HTTP module

Angular 5 Attempting to create a function that will generate a resource on my API using Angular has proven to be a challenge. The "employee.service.ts" file contains a method named "saveEmployee" which is triggered by a function called "addEmployee" locate ...

TypeScript: Defining a custom type based on values within a nested object

I'm attempting to generate a unique type from the value of a nested object, but encountering failure if the key is not present on any level of nesting. Can someone point out where I might be making a mistake? const events = [ { name: 'foo&apos ...

Searching for attributes in a JSON document

Currently, I am dealing with a results API that provides me with a JSON file. My goal is to search for a specific property within this file. To achieve this, I first push the JSON data into an empty array and then iterate over it to retrieve the first obje ...

Return true for cucumber datatable in typescript without fail

I am facing an issue where the following step definition always returns true even for incorrect data from the dataTable. Can someone assist me in correcting the syntax in TypeScript with Chai assertions? Then(/^Verify the following details in report$/, a ...

Failure to deliver messages through socket.emit

Check out the following JavaScript code snippet: `var express = require('express'); var app = express(); var http = require('http').Server(app); var path = require("path"); var io = require('socket.io')(http); app.get(&apos ...

Issue accessing member value in inherited class constructor in Typescript

My situation involves a class named A, with another class named B that is inherited from it. class A { constructor(){ this.init(); } init(){} } class B extends A { private myMember = {value:1}; constructor(){ super(); ...

Passing backend variables/data to AngularJS in Express JS

As a newcomer to express js, I appreciate your patience with me. I've been diving into "MEAN Web Development" by Amos Q. Haviv and finding it to be an excellent read. However, there's one part that's leaving me puzzled. It seems that in or ...

Animated CSS Checkmark Design

How can I create an animated Check-mark using CSS with SVG animation? I attempted the following code but it doesn't seem to be working. Any suggestions? DEMO: https://jsfiddle.net/b7Ln0jns/ CSS: @import "bourbon"; $color--green: #7ac142; $curve: c ...

jQuery when - anticipate the fulfillment of multiple success/done callbacks

When using $.when to determine when an array of ajax promises are finished, I have noticed that although the ajax calls themselves are completed when $.when fires, their callbacks and done functions are not. How can I make sure to wait for the callbacks to ...

Looping through data and converting it into a JSON format can

Can anyone help me figure out how to work through this JSON data using VUE? I'm having trouble accessing keys that v-for can't seem to reach: [ { "Lavandería": { "id": 1, "name": "Lavandería", "i ...

Reduce code length for generating DOM fragment with jQuery

I'm currently working on generating a tree of elements that will be used as an input for JsTestDriver unit tests. I've got some code to create this tree which involves using Document Object Model methods in JavaScript. I'm wondering if there ...

When utilizing the package, an error occurs stating that Chart__default.default is not a constructor in chart.js

I have been working on a project that involves creating a package with a react chart component using chart.js. Everything runs smoothly when I debug the package in storybook. However, I encountered an error when bundling the package with rollup, referenc ...

Determining the orientation of an image in JavaScript

Currently, I am attempting to determine the orientation of images using JavaScript in order to apply a specific class to them. This process seems to be functioning correctly on Firefox, but is presenting challenges on other browsers. It appears to work bet ...

Is there a way for me to view the properties within the subcomponents?

Working on a project to create a bulletin board using React, following the official documentation. Decided to consolidate all actions related to the bulletin board into one alert component called AlertC. In the Form onSubmit statement, if the title is tr ...

Using Angular/Typescript to interact with HTML5 Input type Date on Firefox (FF)

Are there any Angular/Typescript projects that are completely built without relying on third-party libraries? I am encountering problems with Firefox and IE11. It works fine on Chrome where the value can be read, but the calendar does not display when us ...

What are the steps to gather user data and generate a roster of individuals currently online?

I am currently working on a way to gather information about the users who are currently logged into my website. Here's how it works: When a user enters my website, they have the option to choose a nickname using an input box. Then, there are five diff ...

Locate the parent element that has the smallest amount of space taken up by its child elements

My goal is to determine which container, among several <divs>, each containing multiple child <divs> of varying sizes, has the smallest amount of space covered by the child elements. <div class="container" id="first"> ...

What is the best way to iterate over an Angular HTTP Response?

As a newcomer to Angular, I am working on mastering the process of uploading files and calling an API for validation. The API responds with a list of JSON validation errors based on specific file values. I am currently struggling to iterate through these ...

The function threw an error: "TypeError: this.registeredUserArray.some is not a function"

I have been attempting to store a registered user object inside localstorage. However, when I try to retrieve or set those values from localstorage in an array and parse it back to an object, I encounter an error stating that ".push" or ".some" is not a ...

Switching the background image of a div when hovering over a particular list item

Here is my HTML: <li><a href=""><div class="arrow"></div>List Item</a></li> I'm looking to change the background image of the "arrow" class when hovering over the "List Item" with a mouse. The "arrow" class repres ...