Efficient ways to efficiently exclude items in ES6

I am dealing with an array that contains nested objects.

Is there a way to eliminate all key/value pairs that have an underscore at the beginning?

For instance:

{ id: 1,  _link: true } => { id, 1 }

Below is a more detailed example of the data:

{
    "data": [{
        "name": "te4ste",
        "projectId": 1,
        "productAndServicesCategoryList": [{
                "name": "b",
                "productAndServicesId": 1,
                "productAndServicesItemList": [{
                    "name": "w",
                    "productAndServicesCategoryId": 2,
                    "description": "w",
                    "version": null,
                    "createdDate": "2019-04-09T23:17:46.857Z",
                    "createdById": null,
                    "lastModifiedById": null,
                    "deleted": false,
                    "_links": {
                        "self": {
                            "href": "projects/services/contact-emails/emails/2"
                        }
                    },
                    "id": 2
                }],
                "description": "b",
                "version": null,
                "createdDate": "2019-04-09T22:24:37.508Z",
                "createdById": null,
                "lastModifiedById": null,
                "deleted": false,
                    "id": 2
            },
            {
                "name": "a",
                "productAndServicesId": 1,
                "productAndServicesItemList": [{
                    "name": "c",
                    "productAndServicesCategoryId": 1,
                    "description": "c",
                    "version": null,
                    "createdDate": "2019-04-09T22:24:46.332Z",
                    "createdById": null,
                    "lastModifiedById": null,
                    "deleted": false,
                    "_links": {
                        "self": {
                            "href": "projects/services/contact-emails/emails/1"
                        }
                    },
                    "id": 1
                }],
                "description": "a",
                "version": null,
                "createdDate": "2019-04-09T22:24:32.717Z",
                "createdById": null,
                "lastModifiedById": null,
                "deleted": false,
                    "id": 1
            }
        ],
        "description": "testset",
        "version": null,
        "createdDate": "2019-04-09T22:24:22.563Z",
        "createdById": null,
        "lastModifiedById": null,
        "deleted": false,
            "id": 1
    }],
    "total": 1
}

Answer №1

A recursive function can be created to analyze the type of object provided and react accordingly. For arrays, each item is passed back, while for objects, keys are removed and children are passed back. This process modifies the objects in place:

let data=  [{"name": "te4ste","projectId": 1,"productAndServicesCategoryList": [{"name": "b","productAndServicesId": 1,"productAndServicesItemList": [{"name": "w","productAndServicesCategoryId": 2,"description": "w","version": null,"createdDate": "2019-04-09T23:17:46.857Z","createdById": null,"lastModifiedById": null,"deleted": false,"_links": {"self": {"href": "projects/services/contact-emails/emails/2"}},"id": 2}],"description": "b","version": null,"createdDate": "2019-04-09T22:24:37.508Z","createdById": null,"lastModified... 

function remove_s(obj){
    if (!obj || typeof obj !== 'object') return
    Object.keys(obj).forEach(k => {
        if (k.startsWith('_')) delete obj[k]
        else remove_s(obj[k])
    }) 
}

remove_s(data)
console.log(data)

Answer №2

const removeUnderscoreKeys = (arr) => {
    return arr.map(object => {
        const result = {};
        Object.keys(object)
            .filter(key => key[0] !== '_')
            .forEach(key => result[key] = object[key]);
        return result;
    });
}

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

Tips on building an immersive interactive panoramic website

I have a vision for a website that will simulate being in a room, where users can explore the space with limited panoramic views - allowing them to look up/down 30 degrees and left/right 45 degrees. In addition, I would like to integrate interactive object ...

Peruse a spreadsheet for relevant information

I am currently facing an issue with a search bar that I implemented to filter through a table. However, for some reason, the filtering function does not seem to work on the tbody section of the table. The content in the tbody is generated dynamically usi ...

Arranging DataTable by the newest date

I need to change the default sorting of a table from old date to recent date (1st column). Here is the code I have been trying: <script> $(document).ready( function () { $('#table_id').DataTable({ dom: 'B<"cle ...

Efficiently managing routes by segmenting them into distinct files

My Express app is structured in the standard Express 4 format, with dependencies at the top, followed by app configuration, routes, and finally the listen function. I'm currently working on organizing my routes into categorized files (e.g., routes/au ...

Swap the existing div with a fresh div using jQuery or JavaScript

Seeking a straightforward method to swap out a div with a different div, ensuring cross-browser compatibility with JavaScript or jQuery. Below is a code snippet to demonstrate. The goal is to replace "myDiv-B" with a new div: <div id="myDiv-C">{% in ...

Exploring Angular's nested categories with the power of *ngFor loop

I am facing a challenge with an undefined number of arrays that can be nested without limit. This is for the "filtering" section on a page where products are listed. However, I am struggling to dynamically create this structure on the HTML side. [ { ...

Navigating specific elements within ReactORTraversing designated components

Trying to iterate through specific elements in React to render a portion of an array for each view. The rendering of the array should start from ArrayIndexStart and end at ArrayIndexEnd. Here is the current implementation: const ObjectArray = [ {" ...

Upon transitioning between router pages, an error message pops up saying "Vue Socket.io-Extended: this.$socket.$subscribe is not a

I have created a basic Vue application that is designed to connect to a NodeJS server using websockets. My setup involves the use of socket.io-extended for handling the connections. After following the documentation and implementing the websocket connect ...

Utilize JavaScript code from an npm package to incorporate its functionality within your program

I have recently integrated the htmlhint library into my development workflow. I am able to execute it via the command line on any HTML file using the following command: npx htmlhint src/test-file.html Upon running this command, the file is linted and any ...

Persist data in vuex with commit objects

Currently, I am attempting to retrieve objects from an axios response using the $store.commit('fetchFunction', response.data) method. I aim to access this data globally in my SPA (vue-router) by using computed in App.vue (the root component). Her ...

Issues with calculating SUM in MySQL within a Node.js Express application using EJS template

I am currently working on developing a dashboard for my Node.js project. The aim is to calculate the sum of certain values for an overview. While the SELECT statement works fine in my MySQL database, when I incorporate it into my Node project, I do not rec ...

JavaScript code does not seem to be functioning properly on my computer, but it works perfectly fine on

While the code functions perfectly in JSFiddle, it seems to fail when I try to implement it in an HTML file. Despite my efforts, I am unable to pinpoint the source of the issue. If you'd like to view the working version, here is the Fiddle demo. Bel ...

Unable to retrieve a variable from within this function

Having trouble accessing the parameter timesheet which is an object. I can access it in one area but not in another: "// Can access timesheet here" but not: "// Can't access timesheet here" Here's the code snippet: function d(obj, timesheet ...

Combining PHP sessions with Vue and Node.js

Currently, I have a PHP application that handles user authentication, MySQL queries, and relies on the $_SESSION cookie for session management. Despite everything working smoothly, I realized the need to enhance the frontend of my application, prompting t ...

The custom attribute in jQuery does not seem to be functioning properly when used with the

I am currently working with a select type that includes custom attributes in the option tags. While I am able to retrieve the value, I am experiencing difficulty accessing the value of the custom attribute. Check out this Jsfiddle for reference: JSFIDDLE ...

Ways to toggle the visibility of components in React for creating a step-by-step form functionality

I am a React beginner and I need help with showing and hiding parts of my code simultaneously. In the code below, I want only the "step_one" class to be visible on load, while the "step_two" class should remain hidden. When I click on SUBMIT, I want the "s ...

The problem of undefined icons in Material UI's Stepper StepLabel

Having some trouble incorporating a custom Step Label Icon within the nodes of the Stepper Component provided by Material UI. I want to add an icon to each circle, similar to what is shown in this Material UI demo: https://i.sstatic.net/WLOcS.png However, ...

Arrange the elements within each subset of a multi-dimensional array based on the value in a specific column

I am looking to organize the subarrays in the following array based on their value. [ 'bwin' => [ ['bookie' => 'bwin', 'id_bookie' => 178537, 'value' => 6.00, 'bet' => 1 ...

Switch out string parameters with an array value using its corresponding index

Is there a built-in PHP function that can take a string and an array as parameters, and then replace the placeholders in the string with their corresponding values from the array? For example: $myString = "{days} days left for {holiday}"; $params = array ...

Programmatically adding route resolve in Angular using $routeProvider

Is it possible to dynamically add Angular's resolve after it has been initially defined in the app? Let's say we have a setup with routes like this: app.config(['$routeProvider', function ($routeProvider) { $routeProvider ...