Removing a child node in a JSON data structure

I am dealing with the following JSON data. My goal is to remove only the children nodes from the array while keeping the rest of the content intact.

{
"model_type_name": "portfolio",
"hier_model_type_name": "portfolio",
"object_type": "product",
"gen_new_flag": "n",
"mkt_map_req_flag": "n",
"rule_based_flag": null,
"custom_price_type": null,
"hier_id": 468299069,
"hier_name": "AMS",
"parent_hier_id": 1,
"parent_hier_name": "Portfolio",
"level": "2",
"isLeaf": "0",
"parentage": "\\Portfolio\\AMS",
"hier_gen_new_flag": "y",
"hier_child_gen_new_flag": "y",
"hier_entity_role": "parent",
"hier_child_entity": "portfolio",
"hier_rel_type_name": "portfolio hierarchy",
"hist_flag": "y",
"hier_hist_flag": "y",
"rls_type": null,
"mass_updt_flag": null,
"children": [
    {
        "model_type_name": "dummy",
        "hier_model_type_name": "portfolio",
        "object_type": "product",
        "gen_new_flag": "n",
        "mkt_map_req_flag": "n",
        "rule_based_flag": null,
        "custom_price_type": null,
        "hier_id": 469444670,
        "hier_name": "Integrated Solutions",
        "parent_hier_id": 468299069,
        "parent_hier_name": "AMS",
        "level": "3",
        "isLeaf": "0",
        "parentage": "\\Portfolio\\AMS\\Integrated Solutions",
        "hier_gen_new_flag": "y",
        "hier_child_gen_new_flag": "y",
        "hier_entity_role": "parent",
        "hier_child_entity": "portfolio",
        "hier_rel_type_name": "portfolio hierarchy",
        "hist_flag": "y",
        "hier_hist_flag": "y",
        "rls_type": null,
        "mass_updt_flag": null,
        "children": [
            {
                "model_type_name": "dummy",
                "hier_model_type_name": "portfolio",
                "object_type": "product",
                "gen_new_flag": "n",
                "mkt_map_req_flag": "n",
                "rule_based_flag": null,
                "custom_price_type": null,
                "hier_id": 469444678,
                "hier_name": "Healthcare",
                "parent_hier_id": 469444670,
                "parent_hier_name": "Integrated Solutions",
                "level": "4",
                "isLeaf": "1",
                "parentage": "\\Portfolio\\AMS\\Integrated Solutions\\Healthcare",
                "hier_gen_new_flag": "y",
                "hier_child_gen_new_flag": "n",
                "hier_entity_role": "parent",
                "hier_child_entity": "portfolio",
                "hier_rel_type_name": "portfolio hierarchy",
                "hist_flag": "y",
                "hier_hist_flag": "y",
                "rls_type": null,
                "mass_updt_flag": null,
                "children": null,
                "hierGenNewFlag": true,
                "releaseDriven": false,
                "genNewFlag": false,
                "hierChildGenNewFlag": false,
                "massUpdateFlag": false
            }
        ],
        "hierGenNewFlag": true,
        "releaseDriven": false,
        "genNewFlag": false,
        "hierChildGenNewFlag": true,
        "massUpdateFlag": false
    }
],
"hierGenNewFlag": true,
"releaseDriven": false,
"genNewFlag": false,
"hierChildGenNewFlag": true,
"massUpdateFlag": false

}

Here's what I've tried so far, but unfortunately, it's not working as expected. Any help would be greatly appreciated.

for(var i=0; i< $scope.selectedNode.length; i++){
                        var obj = scope.selectedNode[i];
                        for(var k in obj){
                            if(k == "children"){
                                 if(!obj[k]){
                                     delete $scope.selectedNode.children;
                                 }
                             }
                        }
                    }   

Answer №1

The issue arises from the following line:

if(obj[k]){

Only when the value is true, will the children be removed. In JavaScript, an object always evaluates to true. (You can test this by typing !!{} in your browser console).

You can choose to either eliminate the entire condition or remove the '!' symbol.

Answer №2

To delete a node from an object, simply use the following method:

delete object.node;

IMPORTANT

When dealing with objects, avoid using object.length as it will not provide any output. Instead, utilize Object.getLength(object);

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

submission not being processed on form

I've spent the last 3 hours searching for this elusive error, but to no avail. It seems that the onsubmit function is not triggering for some unknown reason. My goal is to ensure that the user inputs a non-negative number in each field. <!DOCTYP ...

Is there a way to exclude specific routes in AngularJS ui router?

In my current web application, I am utilizing the ui-router to manage routing. Within one of my views, there is a canvas that interacts with a third-party library which dynamically loads images through HTTP GET requests. However, due to ui.router's $u ...

Juggling between setting state in React Native and saving in asyncStorage simultaneously

I have developed a react native app module that tracks health statistics, specifically focusing on weight. When the dashboard loads, there is an empty component with a button that opens an editor modal. This modal provides a text input where the user can e ...

Guide to utilizing a directive for dynamic template modifications

I am facing a challenge with this specific instruction. angular.module('starter.directive', []) .directive('answer', ['Helper', function (Helper) { return { require: "logic", link: function ...

Determining the most recent array within an array object in PHP

My goal is to extract data from a JSON object, transform it into an array of objects, and then determine the latest array within this structure based on a specific set of values. For example: // Array structure [ [response] => [ [0] => [ ...

When attempting to post data using jQuery, an object is encountered that does not have a parameterless constructor

Here is the code snippet I am using with jQuery to post data and register a band: var formData = new FormData(); var file = document.getElementById("CoverPicture").files[0]; formData.append("file", file); var Name = $('#Name').val(); var Genre = ...

What's preventing the `@change` trigger from functioning properly with v-data-picker?

In my Vue.js application, I am utilizing the v-calendar package. I am trying to pass selected date range values to the parent component. However, why is the @change trigger not working? Parent.vue: <template> <div> <Child @set ...

Tips for utilizing innerHeight for a div during both window loading and resizing tasks?

I'm currently working on calculating the top/bottom padding of a div (.content) based on its height, and updating it upon loading and resizing the window. The goal is to have it centered nicely next to another div (.character) positioned beside it. I ...

Can you please point out the location of the error in the Java Script code

Our application is developed using Yii2 framework and incorporates Kartik's star-rating widget. However, there seems to be an error in the JavaScript code: Error message from console: Check out the problematic code snippet: <?php $js = ...

Attempting to retrieve an element by its ID from a div that was dynamically loaded using AJAX

I am having trouble retrieving the value of an element with getElementById from a div that is loaded via ajax. Let me explain: In 'example.php' I have the following JavaScript code: <script type= "text/javascript"> var page=document.getE ...

Encountering issues with the Sequelize Model.prototype.(customFunction) feature malfunctioning

While attempting to define a customFunction within the Sequelize model, I encountered an error: TypeError: user.getJWT is not a function at User.create.then (/projects/test/a/app/controllers/UserController.js:22:29) Below is the code snippet from ...

Handling TextChanged Event of a TextBox in ASP.NET using C#

I'm currently designing a POS screen that allows barcode scanning directly into a textbox. I want to implement a code behind procedure that adds the barcode-related data to the grid as soon as the textbox text changes. This is how my textbox looks: &l ...

Reactivity in Vue 3 with globalProperties

When attempting to migrate a Vue 2 plugin to Vue 3, I encountered an issue in the install function. In Vue 2, I had code that looked like this: install(Vue, options) { const reactiveObj = { // ... }; Vue.prototype.$obj = Vue.observable(reactiveO ...

POST request returned a null response in the xhr.responseText

Check out the structure of my JavaScript code: var xhr = new XMLHttpRequest(); xhr.open("POST", "http://myajaxurl.com/lyric", true); var data = "lyric"; xhr.onreadystatechange = function() { if (xhr.readyState == 4) { console.log(xhr.responseText); ...

Having difficulty obtaining accurate window height in Chrome

I am currently facing an issue with determining the accurate width and height of the browser window in Google Chrome. Interestingly, the size appears to be correct in Firefox, but I have not tested it on other browsers. Despite setting the doctype to !DOC ...

Application utilizing Meteor to connect with external websites or applications

Hey everyone, I'm in the process of developing an application that features a directory of stores. One key requirement is that each store has a unique view created with either Flash or JavaScript. The special view components have already been develope ...

Adjust Element Width Based on Scroll Position

I'm attempting to achieve a similar effect as seen here: (if it doesn't work in Chrome, try using IE). This is the progress I've made so far: http://jsfiddle.net/yuvalsab/op9sg2L2/ HTML <div class="transition_wrapper"> <div ...

Photos failing to load in the image slider

Although it may seem intimidating, a large portion of the code is repetitive. Experiment by clicking on the red buttons. <body> <ul id="carousel" class="carousel"> <button id="moveSlideLeft" class="moveSlide moveSlideLeft"></button& ...

Is it possible to include a local directory as a dependency in the package.json file

As I work on developing an npm package alongside its application, I find myself constantly making small changes to the package. Each time I make a change, I want to run the application again for testing purposes. The package is included as a dependency in ...

An array becomes undefined once the previous array is removed

Consider the following code snippet: using the splice method, a specific item from Array1 is retrieved and stored in a variable called Popped. Next, Popped is added to array2. However, if we then delete the value from Popped, why does array2 become undef ...