Is there a way to eliminate an object from a multidimensional nested array in JavaScript and retrieve the parent array?

Can anyone help me figure out how to delete the "fields" object with id 47 from this nested array using JavaScript and return the entire parent array?

[{
    "id": 10,
    "name": "phone",
    "fields": [
        {
            "id": 31,
            "name": "cellphone",
            "fields": [
                {
                    "id": 47,
                    "name": "android"
                }
            ]
        },
        {
            "id": 32,
            "name": "landline"
        }
    ]
},
{
    "id": 12,
    "name": "document"
},
{
    "id": 90,
    "name": "document-name",
    "fields": [
        {
            "id": 91,
            "name": "new-name"
        }
    ]
}]

I've attempted to solve this issue using a filter function, but it seems I'm making a mistake in the implementation. Can somebody provide guidance?

private getUpdatedData(data, id, searchKey = 'fields') {
    data.forEach(function(ele) {
      if(ele.id === id && ele[searchKey]) {
         ele = ele[searchKey].filter(s => s.id === id);
      } else if(ele.id === id && !ele[searchKey]) {
         data = data.filter(s => s.id === id)
      } else if(ele[searchKey]){
         this.getUpdatedData(ele[searchKey], id, searchKey);
      }      
    }.bind(this));
    return data;    
  }

Answer №1

Instead of using the filter method, you can utilize splice to eliminate the object from an array.

function updateData(data, id, searchKey = 'fields') {
    data.forEach(function(item) {
      if (item.id === id && item[searchKey]) {
         item = item[searchKey].filter(s => s.id === id);
      } else if (item.id === id && !item[searchKey]) {
        data.splice(0, 1);
      } else if (item[searchKey]) {
         updateData(item[searchKey], id, searchKey);
      }
   }.bind(this));
   return data;
};

Answer №2

To achieve this, you can utilize a recursive filter function.

data = [{
    "id": 10,
    "name": "phone",
    "fields": [
        {
            "id": 31,
            "name": "cellphone",
            "fields": [
                {
                    "id": 47,
                    "name": "android"
                }
            ]
        },
        {
            "id": 32,
            "name": "landline"
        }
    ]
},
{
    "id": 12,
    "name": "document"
},
{
    "id": 90,
    "name": "document-name",
    "fields": [
        {
            "id": 91,
            "name": "new-name"
        }
    ]
}]

const filterId = (data, id) => {
  if(!Array.isArray(data))
    return data
    
  return data.filter(item => {
    if('fields' in item)
        item.fields = filterId(item.fields, id)
    return (item.id === undefined || item.id !== id)
  })
}
const filtredData = filterId(data, 47)
console.log(JSON.stringify(filtredData, null, 4))

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

JavaScript recursive reduce function

Looking to filter through an Array of objects and extract only those with the key is_enabled=true from another Array of objects. Structure of the data: [ { 'id': 1, 'label': 'Label1', 'option ...

What steps should I take in order to ensure that NPM commands run smoothly within Eclipse?

I have a functional workflow that I'm looking to enhance. Currently, I am developing a JavaScript library and conducting smoke tests on the code by using webpack to bundle the library and save it to a file that can be included in an HTML file for test ...

Determine the RGB color values for specific coordinates within Adobe Illustrator

Currently exploring ExtendScript for JavaScript in Adobe Illustrator 2015. Is there a method to retrieve RGB values based on coordinates within the code below? // initializing document var doc = app.activeDocument; // defining x and y coordinates for colo ...

ReactJS: Want to update card design by utilizing the onClick event handler

Currently, I am aware that there will be a need to refactor this code later on to separate things into their own components. However, due to time constraints, I have to wire this up as is at the moment. To achieve this, I utilized array.map() to create car ...

Navigate post Ajax call

When I make an unauthenticated GET request using AJAX, my server is supposed to redirect my application. However, when I receive the redirect (a 303 with /login.html as the location), the response tab in the Firebug console shows me the full HTML of the lo ...

Custom control unable to display MP3 file

Hey, I came across this awesome button that I am really interested in using: https://css-tricks.com/making-pure-css-playpause-button/ I'm currently facing two issues with it. First, I can't seem to play the sound. I've placed the mp3 file ...

To dismiss a popup on a map, simply click on any area outside the map

Whenever I interact with a map similar to Google Maps by clicking on various points, a dynamically generated popup appears. However, I am facing an issue where I want to close this popup when clicking outside the map area. Currently, the code I have writte ...

What is the best way to send a prop for inline styling in a React component that contains an array of data?

My ShowData component is responsible for rendering in both my App.js and index.js files. import React from "react"; import SwatchData from "./SwatchData"; import { DataTestContainer } from "./DataTestContainer"; function ShowData(props) { const DataCom ...

when input event occurs automatically upon returning to the page

<input type='text' class='binp'> $('.binp').on('input', function(){ alert('lorem'); }); After entering text into the .binp input field and navigating to another page, returning using the browser ...

When iterating through a JavaScript object, opt for utilizing references instead of repeatedly specifying the path

for (var element in array[index1][index2][index3].property) { alert(array[index1][index2][index3].property[element].data); } Is there a more succinct way to achieve the same result by referencing the object directly like this: for (var ...

Is there a way to pause the slideshow? Are there any ways I can enhance the code to make it more efficient?

Currently, I am testing a slideshow that automatically transitions every 1 second. I have set it up to pause when it reaches the first image. However, when it stops on the initial image and I click the next button, nothing happens. If I try to interact wit ...

Ways to verify the presence of users in the Database

I have successfully retrieved the data with the code below, but I am encountering issues with my script's if and else statements. Any tips or advice on how to improve this functionality? server.post('/like', (req, res,next) => { var ...

Error in Node.js: The res.send method is undefined

I'm having some issues with my first attempt at creating a simple Counter Strike API bot using nodeJS. The problem lies with the res.send function, as I keep getting an error message saying "res.send is not a function" every time I try to use it. Movi ...

Leveraging ng-switch for template swapping

I'm currently facing an issue in my Angular app where I want to switch from a "sign in" form to a "sign up" form when the user clicks on the "Sign Up" button, but nothing happens upon clicking the button. The sign-in form persists on the screen withou ...

The Angular Http Interceptor is failing to trigger a new request after refreshing the token

In my project, I implemented an HTTP interceptor that manages access token refreshing. If a user's access token expires and the request receives a 401 error, this function is designed to handle the situation by refreshing the token and re-executing ...

AngularJS binding variables to HTML tag attributes

Currently, I am going through the tutorials and documentation for Angularjs that is provided on the official Angularjs website. One of the examples involves adding a select box for ordering which looks like this: <select ng-model="orderProp"> ...

Node.js powered file uploading on the Heroku platform

After attempting to upload a file to Heroku using https://www.npmjs.com/package/express-fileupload, I encountered an error. It worked fine on my PC, but on Heroku, I received the following error message: {"errno":-2,"code":"ENOENT","syscall":"open","path" ...

Update the displayed number on the input field as a German-formatted value whenever there is a change in the input, all while maintaining

In German decimal numbers, a decimal comma is used. When formatting, periods are also used for grouping digits. For example, the number 10000.45 would be formatted as 10.000,45. I am looking to create an input field (numeric or text) where users can input ...

Error Arises When React Components Are Nested within Objects

I'm encountering a peculiar issue with my component. It works perfectly fine when retrieving data from State at a high level, but as soon as I try to access nested objects, it throws an error: "TypeError: Cannot read property 'name' of undef ...

Re-rendering components using arrow functions

Using an arrow function, I have implemented a feature to toggle a div and show/hide a button based on the div's visibility. toggleDeliveryDiv = () => { document.getElementById('btn_collapse_delivery').click(); this.s ...