Delete a particular item from a JSON object in real-time using TypeScript/JavaScript

Upon examining the JSON data provided, it contains a node called careerLevels which includes inner child elements.

input = {
            "careerLevelGroups": [
                {
                    "201801": 58,
                    "201802": 74,
                    "careerLevel": "Analyst",
                    "careerLevels": [
                        {
                            "201801": 29,
                            "201802": 37,
                            "careerID": "10000100"
                        },
                        {

                            "201801": 29,
                            "201802": 37,
                            "careerID": "10000110"
                        }
                    ]
                },
                {

                    "201801": 58,
                    "201802": 74,
                    "careerLevel": "Consultant",
                    "careerLevels": [
                        {

                            "201801": 29,
                            "201802": 37,
                            "careerID": "10000080"
                        },
                        {

                            "201801": 29,
                            "201802": 37,
                            "careerID": "10000090"
                        }
                    ]
                }
]}

My goal is to programmatically remove all instances of the careerLevels node from this JSON and only retain the following information:

output= {
            "careerLevelGroups": [
                {
                    "201801": 58,
                    "201802": 74,
                    "careerLevel": "Analyst"

                },
                {

                    "201801": 58,
                    "201802": 74,
                    "careerLevel": "Consultant"

                }
]}

I initially attempted to achieve this by using the code snippet below:

let strippedJson = copyObject(mergedJson);
    delete strippedJson.careerLevels; // remove careerLevels but this is not doing anything.

Realizing the need for a different approach, I believe that something similar to the following pseudocode might be more suitable:

input.forEach(element => {element.delete}) // something like this

Answer №1

Below is a code snippet you can experiment with:

let result = JSON.parse(JSON.stringify(input));
result.careerLevelGroups.forEach(grp => delete grp.careerLevels);

Answer №2

Utilize the array Map method to loop through the elements in the careerLevelGroups array and then remove the careerLevels property from each object :

var jsonObj = {
"careerLevelGroups": [{
"201801": 58,
"201802": 74,
"careerLevel": "Analyst",
"careerLevels": [{
"201801": 29,
"201802": 37,
"careerID": "10000100"
},
{

"201801": 29,
"201802": 37,
"careerID": "10000110"
}
]
},
{

"201801": 58,
"201802": 74,
"careerLevel": "Consultant",
"careerLevels": [{

"201801": 29,
"201802": 37,
"careerID": "10000080"
},
{

"201801": 29,
"201802": 37,
"careerID": "10000090"
}
]
}
]
};

var res = jsonObj.careerLevelGroups.map(obj => {
delete obj.careerLevels
return obj;
});

console.log(res);

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

Eliminate error class in jQuery Validate once validation is successful

I'm having an issue with the jQuery Validate plugin. Even after a field is successfully validated, the "error-message box" continues to be displayed. How can I remove this box? Here's my code: CSS: .register-box .field .has-error{ border ...

When transmitting a variable from JavaScript to PHP using Ajax, the data appears to be missing

While attempting to pass a simple string variable using an onclick event, I encountered an issue where the request was successful but the response in the console displayed as empty. Additionally, the xvar variable did not come through properly resulting in ...

What is the best way to combine the elements within an array with the elements outside of the array in order to calculate their sum?

The goal is to create a function that determines the winner using two input integers. The function should return the first input if it is greater than the second input. function determineWinner(a, b) { let result = [] for (let i = 0; i < 3; i++) ...

PHP Command Line Interface can effectively parse JSON strings provided as arguments

When utilizing PHP 5.3 and passing a JSON encoded string as an argument via command line... /usr/local/bin/php -q /path/to/script.php {"key":"test","cache":1} ... the code within script.php looks like this: <?php print_r($argv); ?> The output is: ...

Creating a factory function in TypeScript to generate union types

I have developed a unique Factory type that allows me to create factory functions. export type Factory<T> = (state?: Partial<T>) => T; Within my <Avatar /> React component, I have implemented a prop with a union type to accommodate fo ...

Is importing local JSON done synchronously or asynchronously?

Is the process of importing local JSON or text like the example below done asynchronously or synchronously in Create-React-App? import SampleLocalJson from './sample/sampleJson.json' ...

Having trouble with JavaScript not working when clicking an image and toggling a div?

Why isn't the onclick image and toggle div functionality working with JavaScript? I made the change from: <input type="button" id="Showdiv1" name="Showdiv1" value="Show Div 1" onclick="showDiv('div1')" /> to: <img src="https://d ...

Working with arrays in Angular 4 to include new items

I am struggling with the code below: export class FormComponent implements OnInit { name: string; empoloyeeID : number; empList: Array<{name: string, empoloyeeID: number}> = []; constructor() { } ngOnInit() { } onEmpCreate(){ conso ...

Guide on creating a project for developing an npm package

Within my git root project, I am utilizing a git subproject called UIComponents. For instance, my main project is named MyApp and the subproject is UIComponents. Currently, I have cloned the UIComponents repository inside my project folder and added UIComp ...

Exploring ways to create additional file upload fields with distinct names through JavaScript

My latest project involved creating a button that allows users to add a file upload field, a separate button to remove a file upload field, and a counter to keep track of the total number of file upload fields. However, it appears that the fields are not b ...

Having trouble incorporating autocomplete search results into an HTML table using Jquery, Ajax, and JSP

My current project involves an App that utilizes AJAX with jQuery to communicate with a Spring-boot REST controller. While the app is functional, I am facing difficulty in displaying the search results neatly within HTML tables. result Here is a snippet ...

Efficiently managing modules with requirejs and Backbone.Marionette

After organizing the file structure of my web app, utilizing RequireJs and Backbone.Marionette, it now looks like this: |- main.js |- app.js |- /subapp1 |- subapp1.js |- subapp1.router.js |- /subapp2 |- subapp2.js | ...

What is the best way to transfer a resolved promise value to a different function?

Is there a way to pass the value of a returned Promise to another function? I'm looking to extract parsed JSON data and then utilize that response data to send it to a Slack channel. This is my index.js: // Retrieve the data let getData = () => { ...

Exploring Sencha Touch's capabilities with Nested JSON and Associations

Today, I have a technical dilemma that requires some expertise in how Sencha handles JSON parsing and store reading. Let's talk about two models: Order and User: Ext.regModel('Order', { fields: [ {name: 'id', type: 'in ...

React-Redux - Implement a button toggle functionality to display or hide additional information

I am currently working on creating a portfolio. One of the functionalities I am trying to implement is a toggle button that will show or hide the details of a specific work when clicked. I have been learning React and Redux, so this project is a great oppo ...

Connect your Nuxt.js application with Mailchimp for seamless integration

I've tried the solution recommended in this thread, but unfortunately, it's not working for me. Every time I run npm run dev, I encounter an error message: ERROR - Compilation failed with 1 error at 11:21:24 The following dependency was not fo ...

Cover the entire screen with numerous DIV elements

Situation: I am currently tackling a web design project that involves filling the entire screen with 60px x 60px DIVs. These DIVs act as tiles on a virtual wall, each changing color randomly when hovered over. Issue: The challenge arises when the monitor ...

Challenges encountered while compiling Node.js code with ts-node (Error: Cannot use import statement outside a module)

Trying to compile TypeScript code with NodeJS using this command: npx ts-node src/server.ts An error is thrown: SyntaxError: Cannot use import statement outside a module Following the error's instructions: Warning: To load an ES module, set " ...

Trouble with implementing a custom attribute directive in Angular 4 and Ionic 3

Hello, I am currently working on implementing a search input field focus using a directive that has been exported from directives.module.ts. The directives.module is properly imported into the app.module.ts file. However, when attempting to use the direc ...

Verify if the currentRoute begins with a specific text pattern (such as something/something/*...) in Angular

I need to prevent a loader from appearing on certain screens, so I used ngIf on routes where the loader is not necessary. Here's the code snippet from app.component.ts : <router-outlet> <app-spinner></app-spinner> <ngx-ui-load ...