What is the best way to delete a nested child object using a specific identification number?

Here is the current json structure:

$scope.dataList = [{
   CompanyName: null,
   Location: null,
   Client: [{
      ClientId: 0,
      ClientName: null,
      Projects:{
         Id: 0,
         Name: null,
      }
   }]
}];

I'm attempting to

remove client data based on a specific clientid from the list of clients
, but for some reason, the client data is not being removed and there are no error messages being displayed.

Check out the code snippet below:

for (var i = 0; i < $scope.dataList.length; i++)
            {
                for (var j = 0; j < $scope.dataList[i].Client.length; j++)
                {
                    if ($scope.dataList[i].Client[j].ClientId == 101)
                    {
                       $scope.dataList[i].Client.splice(j, 1);
                    }     
                }
            }

Could someone please help me identify what might be wrong with my code?

Answer №1

To remove the item, you can utilize the delete statement as shown below:

for (var i = 0; i < $scope.dataList.length; i++)
            {
                for (var j = 0; j < $scope.dataList[i].Client.length; j++)
                {
                    if ($scope.dataList[i].Client[j].ClientId == 101)
                    {
                       delete $scope.dataList[i].Client[j];
                    }     
                }
            }

However, be cautious as this approach may lead to issues due to the decrement in item count within the loop.

Consider using an alternative method to address this issue.

Answer №2

Here is a solution:

for (let i = 0; i < $scope.dataList.length; i++) {
  for (let j = 0; j < $scope.dataList[i].Client.length; j++) {
    let foundIndex;
    if ($scope.dataList[i].Client[j].ClientId == 101){
      foundIndex = j;
    }
    $scope.dataList[i].Client.splice(j, 1);
  }
}

Fiddle: https://jsfiddle.net/uv3zo0y2/

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

Attempted to display a Google Map within a lightbox, but encountered difficulties in getting it to

I've copied and pasted my code below. It may contain references to Google or Lightbox being undefined, but I'm unsure how to integrate them into the code provided. My goal is to display a Google map within a Lightbox popup, but so far I have been ...

What is the best way to customize the link style for individual data links within a Highcharts network graph?

I am currently working on creating a Network Graph that visualizes relationships between devices and individuals in an Internet of Things environment. The data for the graph is extracted from a database, including information about the sender and receiver ...

AngularJS - Changing Views with Templates

At the moment, I am changing my directives in the following manner. Within my directive: (function(){ 'use strict'; var controller = ['$scope', function ($scope) { }]; angular .module('moduleName' ...

Incorporate JavaScript code into contentWindow

Attempting to utilize a Javascript postMessage function, similar to how it can be done with an iframe, but now with an embed element. The reason for using an embed is due to the bug in IOS devices which causes issues with setting iframe width and height. ...

Executing a MongoDB query can only be successful by utilizing the copy and paste method

Recently, I encountered an unusual issue with MongoDB while attempting to query the database. Specifically, when running a query like db.departments.find({"key": "MEL 301"}), it returned no results. The MongoDB database is hosted on mLab, allowing me to v ...

Deno -> What steps should I take to ensure my codes run smoothly without any errors?

Trying to import locally Experimenting with Deno v1.6.0 in a testing environment Attempting local imports using Deno language Local directory structure: . └── src └── sample ├── hello_world.ts ├── httpRequest. ...

Utilize the power of DOJO JavaScript to implement Reverse AJAX functionality in

Exploring the possibility of implementing Reverse AJAX with the DOJO Javascript framework. Curious if DOJO has built-in support for this feature like other frameworks such as DWR. I am currently working with the most recent version of DOJO - any guidance ...

What is the method for automatically verifying elements within nested ng-repeats?

My div contains ng-repeat elements that are interconnected. Each ng-repeat element has checkboxes, and I want to automatically check the related elements in other ng-repeats when a top ng-repeat element is checked. Here is the actual representation of the ...

Combining multiple rows into one using either mysql or lodash was achieved by Node

Currently in my Javascript framework, I am utilizing the Node MySQL library for executing MySQL queries. I encountered an issue with a left join that resulted in multiple rows being returned. This is because the left join generates duplicate rows with diff ...

Tally up the values of selected checkboxes

  I'm in search of a method to tally up data-values associated with checkboxes. In the example provided below, selecting locations from the checkboxes results in the calculation of primary values, which are displayed in the green box. I also need to ...

Is there a way to select only a single line from an HTML document?

Is there a way to extract just one specific line from an HTML file? Let's say we have the following file: <!DOCTYPE html> <html> <head></head> <body> This is a test string. This is another test st ...

Retrieve the name of the file from a given URL by using JavaScript/jQuery, even when only the directory path is

I need to extract the current filename from the URL using: $currentFile = window.location.pathname.split("/").pop(); This method functions properly when the full path looks like: http://www.yoursite.com/folder/index.php It will return index.php, index. ...

Troubleshooting overload errors within ReactJS: tips and tricks

import React from 'react' import { Link } from 'react-scroll' import "./Protocol.css" import { ANALYTICS, TRADE, USERS, TRADERS, VOTES, ZEROES } from "../../Constants" const Protocol = () => { return ( ...

Angular allows for the utilization of the same URL "/" while serving up distinct templates depending on whether the user is logged in or not

Looking to implement two different templates - one for the landing page for logged out users showcasing the business and another for the dashboard page once a user is logged in. Came across a solution on this particular stack, which explains how to achiev ...

When using AngularJS and PHP together, I encountered an error that stated "

My POST http request is encountering an error with the message Undefined property: stdClass::$number and Undefined property: stdClass::$message. Below are the codes I've been using: smsController.js angular .module('smsApp') .contr ...

Guide to adding sound effects to your Vue 3 app using the Composition API

I'm having trouble setting up a basic button click feature in Vue 3 Composition API to play a sound effect. In my setup function, I have imported an mp3 sound effect from the assets folder and passed it into a ref method with an HTMLAudioElement type, ...

How can dependencies be conditionally imported in a module that is shared between React (Next.js) and React Native?

I am looking to create a shared Typescript module that can be used in both a React (Next.js) web app and React Native mobile apps. This module will be responsible for managing communication with the backend (Firebase) and handling state management using t ...

Reset the dropdown menu in React by setting a disabled option as the default selection

One issue I'm facing is trying to reset some dependent dropdowns that are controlled by react state. The functionality works fine, except when the default option is set as disabled. I came across this code snippet in a fiddle from another stackoverfl ...

Node server encountering issue with undefined data in POST request

I have been working on an Angular2/Node.js application. Everything seems to be working fine when I retrieve an object from the Node server, but I'm facing an issue when trying to post data to the server. The request.body always shows as undefined. Can ...

AngularJS is experiencing an error due to an unidentified provider

Currently, I am in the midst of a project utilizing Asp.Net MVC + AngularJS. Development has been smooth sailing so far, however, upon running it on IIS, an error popped up: Uncaught Error: [$injector:unpr] Unknown provider: nProvider <- n How can I g ...