Sorting through a nested array that is encapsulated within an object

After searching for solutions on how to filter nested arrays, I found multiple sources that mentioned dealing with arrays within other arrays. However, in my particular case, the challenge lies in handling an array nested within an object.

The array in question is structured as follows:

{
    "msg": "OK",
    "blueprint": {
        "result": "OK",
        "blueprint": {
            "id": "a2e63ee01401aaeca78be023dfbb8c59",
            "product": {
                "productName": "Test Product",
                "productId": "AS_12-01",
                "description": "Test Descr.",
                "childProducts": [
                    {
                        "childId": "T1",
                        "parent": "8c59"
                    },
                    {
                        "childId": "T5",
                        "parent": "8c7e"
                    }
                ],
                "components": [
                    {
                        "compId": "C2",     #
                        "leadTime": 21,     # remove
                        "available": false  #
                    },
                    {
                        "compId": "C5",
                        "leadTime": 3,
                        "available": true
                    },
                    {
                        "compId": "C6",     # 
                        "leadTime": 12,     # remove
                        "available": false  # 
                    },
                    {
                        "compId": "C8",
                        "leadTime": 5,
                        "available": true
                    },
                ]
            },
            "owner": "dummy",
            "name": "du_test"
        }
    }
}

My goal is to filter the nested array in such a way that the resulting object retains its structure but excludes any unavailable objects.

{
    "msg": "OK",
    "blueprint": {
        "result": "OK",
        "blueprint": {
            "id": "a2e63ee01401aaeca78be023dfbb8c59",
            "product": {
                "productName": "Test Product",
                "productId": "AS_12-01",
                "description": "Test Descr.",
                "childProducts": [
                    {
                        "childId": "T1",
                        "parent": "8c59"
                    },
                    {
                        "childId": "T5",
                        "parent": "8c7e"
                    }
                ],
                "components": [
                    {
                        "compId": "C5",
                        "leadTime": 3,
                        "available": true
                    },
                    {
                        "compId": "C8",
                        "leadTime": 5,
                        "available": true
                    },
                ]
            },
            "owner": "dummy",
            "name": "du_test"
        }
    }
}

In essence, the desired outcome is to retain the original structure while removing the unavailable objects from the nested array.

Any suggestions on how to accomplish this task?

Answer №1

To update the field, reassign it with the filtered array values

const data = {    
    "msg": "OK",    
    "blueprint": {
        "result": "OK",
        "blueprint": {
            "id": "a2e63ee01401aaeca78be023dfbb8c59",
            "product": {
                "productName": "Test Product",
                "productId": "AS_12-01",
                "description": "Test Descr.",
                "childProducts": [
                    {
                        "childId": "T1",
                        "parent": "8c59"
                    },
                    {
                        "childId": "T5",
                        "parent": "8c7e"
                    }
                ],
                "components": [
                    {
                        "compId": "C2",
                        "leadTime": 21,
                        "available": false
                    },
                    {
                        "compId": "C5",
                        "leadTime": 3,
                        "available": true
                    },
                    {
                        "compId": "C6",
                        "leadTime": 12,
                        "available": false
                    },
                    {
                        "compId": "C8",
                        "leadTime": 5,
                        "available": true
                    },
                ]
            },
            "owner": "dummy",
            "name": "du_test"
        }
    }}

data.blueprint.blueprint.product.components = data.blueprint.blueprint.product.components.filter(({available}) => available)

console.log(data)

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

On startup of the chrome app, read and load a JSON file into a variable

As I develop a chrome app, my goal is to store all configuration defaults in json file(s) alongside other assets. I am currently using AJAX requests to load them, but I'm wondering if there is a more efficient way to handle this. Is there perhaps an o ...

Guide on replacing characters in Blogger using Javascript

I'm trying to change certain characters like [ngu1], [ngu2] to [chanquadi] using the following script: <script type='text/javascript'> var heo1 = document.querySelector(<.post-body>); var heo2 = heo1.replace("[ngu1]", "c ...

Learn how to trigger a re-render in React to update a value stored in local storage

I need assistance in displaying a spinner with a percentage value during file uploads within my React application. To achieve this, I am utilizing Material UI's circular progress. My approach involves making a REST call using Axios to obtain the perce ...

Discover the most extensive trail of 'A's within a character array

Greetings and I would greatly appreciate any assistance! I am in need of developing a program that will scan through a char array read from a file. This program should utilize recursion to identify the longest consecutive path of adjacent 'A's, ...

Struggling to jest mock the useLocation hook in a React component that has been shallow mounted

Currently, I am working on testing a component that relies on the useLocation react hook. Despite my efforts to mock it, I keep encountering an error when trying to access useLocation().pathname because useLocation is undefined. Additionally, I have a que ...

Switching an input field from readonly to editable in ASP.NET Core

MODAL <div class="modal fade" id="residentModal" tabindex="-1" role="dialog" aria-labelledby="residentModalLabel" aria-hidden="true"> <div class="modal-dialog modal-lg& ...

Creating an Array of Arrays

My application requires me to set up a structure like the following: $arrProducts = array( array( “product_id” => “1”, “qty” => 2 "options" => array( optionId_1 => op ...

Generate unique Prometheus gauge names on the fly

Incorporating prom-client into my node application allows me to send statistics to our prometheus platform. To check the availability of different applications, I am initiating a series of requests. In this process, I aim to customize the name of the gauge ...

Issue with updating onclick attribute of popover in Bootstrap 4

My goal is to design a popover in bootstrap 4 with a nested button inside it. However, when I update the data-content attribute of the popover with the button element, the element gets updated but the onclick attribute goes missing. I have experimented wi ...

What are the steps to reset a JavaScript game?

I'm currently working on a JavaScript game project. Once the game is finished, I'd like to give players the option to go back to the main menu by clicking a button, then start a new game by clicking play again. However, I've run into an issu ...

Navigating Dynamic Memory Allocation Between Fortran and C++ Subroutines: Best Practices

Currently, I have a C++ program that performs various tasks and stores data in a dynamically allocated 2D array using the malloc function in C. The program works well, but now I need to access this data in a Fortran program. As of now, I am developing a Fo ...

Managing actions on dynamically generated dropdown options in <select> elements

If I have a function that generates a dropdown, it is called from a parent component where props like state key, array, and onChange function are passed in. The dropdown items are dynamically created from the array. What I want is for the parent's sta ...

Is it possible to trim a video using HTML code?

I am trying to find a way to crop a video using HTML 5. <video id="glass" width="640" height="360" autoplay> <source src="invisible-glass-fill.mp4" type="video/mp4"> </video> Currently, the video has a resolution of 640x360. However ...

Validating AJAX responses

Recently, I have begun working with AJAX and have encountered an issue related to error checking while parsing XML data in JavaScript. The problem arises when I dynamically create an XML file using C code - sometimes I receive an error stating "unable to r ...

The black package in package-lock.json seems to have a mind of its own, constantly disappearing and re

When running npm install, I've noticed that the property packages[""].name in the package-lock.json file is sometimes removed and sometimes added. How can I prevent this change from occurring, as it is causing unnecessary git changes? https ...

Learn the process of creating a webpage that is accessible to users who are signed in through Parse

I created a landing page where users can easily login or register using parseSDK. This feature is currently working well. The next step was building a dashboard page (dashboard.html) that should only be accessible to logged-in users. However, I noticed tha ...

When converting to TypeScript, the error 'express.Router() is not defined' may

Currently, I am in the process of converting my express nodejs project from JavaScript to TypeScript. One of the changes I've made is renaming the file extension and updating 'var' to 'import' for "require()". However, there seems ...

Vertical Dragging Division of Space

I am looking to create a draggable division that separates two areas vertically, similar to the images below: https://i.sstatic.net/AC9Gt.pnghttps://i.sstatic.net/xA4cX.png I found an online example of draggable divs and customized it to suit my needs. I ...

Designing a dynamic HTML dropdown menu using data from a MySQL database

Attempting to pull data from the "aircraft" table in the "aircraft" database for a dropdown menu on an HTML page. Unsure of where to begin as I have no experience connecting the two. This is the desired format: <!DOCTYPE html> <html> <bo ...

Tips for sending an optional parameter to @Directives in Angular 2 using TypeScript

Here is a helpful guide on passing parameters to Angular 2 directives. <p [gridGroup]="gridGroup"></p> My goal is to have the parameter as optional so that it doesn't have to be included in every class referencing the html source. Curre ...