Traverse a nested array of objects within an array of objects in JavaScript to remove a specific entry

Here is the structure of my array:

const array = [
    {
        '12345': [
            {
                name: 'item one',
                numbers: ['12345', '77484'],
            },
            {
                name: 'item two',
                numbers: ['12345', '65456'],
            },
            {
                name: 'item three',
                numbers: ['12345', '33920'],
            },
            {
                name: 'item four',
                numbers: ['12345', '99393'],
            },
        ],
    },
    {
        '67890': [
            {
                name: 'item one b',
                numbers: ['67890', '33232'],
            },
            {
                name: 'item two b',
                numbers: ['67890', '33456'],
            },
            {
                name: 'item three b',
                numbers: ['67890', '77665'],
            },
            {
                name: 'item four b',
                numbers: ['67890', '11234'],
            },
        ],
    },
]
console.log(array);

If I have a dynamic variable like 'item three b', how can I locate and delete that specific entry within the nested arrays?

I'm facing some challenges accessing the deeply nested arrays.

Appreciate any help!

Answer №1

To achieve the desired outcome, you can utilize a forEach loop in combination with findIndex and splice methods to manipulate the data within the array.

const sampleArray = [
    {
        '12345': [
            {
                name: 'item one',
                numbers: ['12345', '77484'],
            },
            {
                name: 'item two',
                numbers: ['12345', '65456'],
            },
            {
                name: 'item three',
                numbers: ['12345', '33920'],
            },
            {
                name: 'item four',
                numbers: ['12345', '99393'],
            },
        ],
    },
    {
        '67890': [
            {
                name: 'item one b',
                numbers: ['67890', '33232'],
            },
            {
                name: 'item two b',
                numbers: ['67890', '33456'],
            },
            {
                name: 'item three b',
                numbers: ['67890', '77665'],
            },
            {
                name: 'item four b',
                numbers: ['67890', '11234'],
            },
        ],
    },
]

sampleArray.forEach(object => {
   Object.values(object).forEach(innerObject => {
   var index = innerObject.findIndex(item => item.name==='item three b');
   if(index>-1){
      innerObject.splice(index,1);
     }
  })
})

console.log(sampleArray);

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

How can I improve my skills in creating efficient Angular routers?

In my Ionic project, I am dealing with an AngularJS routes file that contains a large number of routes, approximately a hundred. The structure is similar to the one provided below. (function() { 'use strict'; angular.module('applicatio ...

Adding Bootstrap 5 component to a create-react-app

Hello there! I appreciate any assistance with my Bootstrap 5 integration in a React app. I'm facing issues with including the Bootstrap component js, and below is the code snippet where I attempt to import it. import "bootstrap/dist/css/bootstrap ...

Issues arise with controlling access due to cache-control and canvas properties

I am attempting to utilize the browser canvas feature to manipulate images that are hosted on cloudfront. My goal is to configure cloudfront in a way that allows the browser to cache images with cache control set to max-age, while still enabling canvas edi ...

Calculate the sum of values in a JSON array with JMESPath

Currently, I am encountering some difficulties while attempting to utilize the `sum` function within `JMESPath`. Despite this, I was able to successfully navigate the search function with multiple conditions. The following statement: let x = search(myData ...

A guide to resolving cross-origin resource sharing issues using a reverse proxy

After creating a JavaScript web application for processing documents, I am now looking to integrate with web services like NLTK-server, TIKA-server, and SOLR for further analysis. While I can successfully access the REST endpoints of these services using c ...

Angular 2 input delay feature

I'm currently working on an application where I need to send an event after input debounce. Here's what I have tried so far: @ViewChild('messageInput') messageInput: ElementRef; private inputTimeOutObservable: any; setTypi ...

Discovering details regarding cookies established by an external domain

Is it possible to retrieve the host address of the domain that created a cookie on my webpage? Here is the scenario I am facing: I am on "domain A" and have a script linked from "domain B". A method on "domain B" sets a cookie on my "domain A". How can ...

Differentiating the angular distinction between setting a variable with ng-click and invoking a function

I've encountered a situation like this before. Let's assume the controller has these variables: $scope.valueArr = ['Hello', 'No', 'Yes']; $scope.myValue = 'Hello'; And there is an ng-repeat as follows: ...

Obtaining the referring URL after being redirected from one webpage to another

I have multiple pages redirecting to dev.php using a PHP header. I am curious about the source of the redirection. <?php header(Location: dev.php); ?> I attempted to use <?php print "You entered using a link on ".$_SERVER["HTTP_REFERER"]; ?> ...

Highlighting neighboring components with the same marker when hovering in Slate JS: a step-by-step guide

// custom mouse over hook function useMouseOver() { const [mouseIsOver, setMouseIsOver] = useState(false); return { mouseIsOver, triggers: { onMouseEnter: () => setMouseIsOver(true), onMouseLeave: () => setMouseIsOver(false), ...

Guide to using the Strapi Upload Plugin: Uploading a file from a remote source using a scheduled task

Utilizing the strapi upload plugin with s3 as the provider has been a seamless experience when making API calls to the upload endpoint on my strapi instance (/upload). However, I am facing a dilemma with a cron job within our repository that monitors image ...

Send various pieces of information using Jquery/Ajax

I have encountered a challenge with my script - it currently only sends one value to the requested URL, but I now need it to handle two values. Unfortunately, I haven't been able to figure out how to do this. Each checkbox on the page is paired with ...

AngularJS (ui-mask) provides a valid input mask feature

i encountered an issue while trying to create an input mask using ui-mask in AngularJs. I want the textarea to turn green when the entered string is correct. However, in my case, the textarea starts off green and then turns red when a word is typed until t ...

Listening for server updates with jQuery

I am currently working on a web application that communicates with a server for database updates. The issue I am facing is that the update process can vary greatly in time, ranging from milliseconds to tens of seconds for larger updates. I would like to im ...

Just for laughs: "The react-redux context value seems to be playing hide and seek; make sure to wrap the component in a <Provider> for it to show up!"

I encountered an issue while attempting to run a basic Jest test on a form React component: ● <LoginForm /> › clicking the validate button › should display page title ...

What sets apart route.use(), route.all(), and route.route() in Express?

Is it possible to replace router.all() with router.use() if the former just matches all methods? Also, what are the differences between using router.use() and router.route()? ...

Creating an optimized dashboard in Next.js: Expert tips for securing pages with specific roles, seamlessly implementing JWT authentication without any distracting "flickering" effect

Given our current setup: We have a backend ready to use with JWT authentication and a custom Role-Based Access Control system There are 4 private pages specifically for unauthenticated users (login, signup, forgot password, reset password) Around 25 priva ...

An issue has been detected by Zone.js where the ZoneAwarePromise `(window|global).Promise` has been unexpectedly replaced

I have recently integrated the Angular2 quickstart code into my existing webpack setup, but I seem to be facing an issue where something is interfering with the promise from zone.js, resulting in an error. Based on my research on Stack Overflow, it appears ...

The menu does not appear when I attempt to right-click on the grid header

Is there a way to add a right-click menu to the grid header? The right-click functionality works on Google links, but not on the grid header. Any suggestions on how to resolve this issue? Below is the code I'm using: http://jsfiddle.net/c7gbh1e9/ $( ...

Top choice for removing items from a list array

Hey there, I'm working with an array of a custom type in Angular: List { task: string; id?: number; status?: boolean; } I'm trying to figure out how to delete elements where List.status == true. I've tried two methods for this. ...