Ways to eliminate a targeted key within a JSON reply

I'm working with a JSON response in postman and need to figure out how to remove a specific key from the data. In this case, I want to remove head_out_timestam - no matter where it is in the object tree.

This needs to be done using javascript. Any help is greatly appreciated!

{
 "soapenv:Envelope": {
      "$": {
          "xmlns:soapenv": "http://schemas.xmlsoap.org/soap/envelope/"
    },
      "soapenv:Header": {
          "f:Routing": {
              "f:Receiver": {
                  "f:Application": "Something"
            }
        }
    },
      "soapenv:Body": {
          "Something": {
              "something_output": {
                  "service_header_out": {
                      "head_out_servercode": "Some",
                      "head_out_timestam": "2019-06-18-11.32.13.570127",
                }
            }
        }
    }
}

}

Answer №1

To efficiently remove a specific key from an object, you can perform a recursive search for the key and then delete it once found.

Consider the following approach:

var data = {
"user1": {
    "name": "John",
    "age": 30
},
"user2": {
    "name": "Jane",
    "age": 25
}
}

var removeKey = (data, target) => {
  Object.keys(data).forEach((key) => {
    if (key === target) {
      delete data[key];
    } else if (typeof data[key] === 'object') {
      removeKey(data[key], target);
    }
  });
  return data;
}

console.log(removeKey(data, 'age'));

Note: You have the option to utilize Object.keys(obj).forEach or for ... in loops for iterating through objects.

Answer №2

var data = {
    "soapenv:Envelope": {
        "$": {
            "xmlns:soapenv": "http://schemas.xmlsoap.org/soap/envelope/"
        },
        "soapenv:Header": {
            "f:Routing": {
                "f:Receiver": {
                    "f:Application": "Something"
                }
            }
        },
        "soapenv:Body": {
            "Something": {
                "something_output": {
                    "service_header_out": {
                        "head_out_servercode": "Some",
                        "head_out_timestam": "2019-06-18-11.32.13.570127",
                    }
                }
            }
        }
    }
}

console.log(data["soapenv:Envelope"]["soapenv:Body"]["Something"]["something_output"]["service_header_out"]["head_out_timestam"]);

delete data["soapenv:Envelope"]["soapenv:Body"]["Something"]["something_output"]["service_header_out"]["head_out_timestam"]
console.log(data["soapenv:Envelope"]["soapenv:Body"]["Something"]["something_output"]["service_header_out"]["head_out_timestam"]);

Answer №3

To remove the element head_out_timestam

Follow this approach

 let response={
    "soapenv:Envelope": {
        "$": {
            "xmlns:soapenv": "http://schemas.xmlsoap.org/soap/envelope/"
        },
        "soapenv:Header": {
            "f:Routing": {
                "f:Receiver": {
                    "f:Application": "Something"
                }
            }
        },
        "soapenv:Body": {
            "Something": {
                "something_output": {
                    "service_header_out": {
                        "head_out_servercode": "Some",
                        "head_out_timestam": "2019-06-18-11.32.13.570127"
                    }
                }
            }
        }
    }
    }
    //to eliminate the specified key-value pair 
 

delete response["soapenv:Envelope"]["soapenv:Body"]["Something"]["something_output"]["service_header_out"]["head_out_timestam"]
    
    //Verify the updated response 
    console.log(response);

Answer №4

To remove an element in JavaScript, you can utilize the delete operator as demonstrated below:

delete response["soapenv:Envelope"]["soapenv:Body"].Something.something_output.service_header_out.head_out_timestamp;

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

Executing a SQL query using a JavaScript variable as a parameter

I am currently working on a website form that includes a select menu populated with data from an SQL table using a loop. The form is being displayed using JavaScript scripts, which are functioning perfectly. However, I am facing an issue in the final step ...

What is the best way to choose the initial element in every group using jQuery?

If we have the following HTML input: <p>A</p> <p>B</p> <p>C</p> <div>D</div> <p>E</p> <p>F</p> <p>G</p> We can select B, C, F and G using the following code: $('p + ...

Go to the identical page with a message embedded in it

Creating a login page using JSP involves an index.jsp file which contains the form and javascript scriplets. The connectivity to an Oracle database and validation of username and password are handled in check1.jsp. The problem arises after entering the us ...

The module 'myapp' with the dependency 'chart.js' could not be loaded due to an uncaught error: [$injector:modulerr]

Just starting out with Angular.JS and looking to create a chart using chart.js I've successfully installed chart.js with npm install angular-chart.js --save .state('index.dashboard', { url: "/dashboard", templateUrl ...

Tips for customizing the background color of the MUI Menu Popover within a TextField that has the select property

In my quest to customize the appearance of a popover or menu in a TextField with the 'select' property, I referred to MUI customization docs for guidance. Successfully changing the text and label color of a TextField using the code below: const u ...

What is the best way to access a variable from a .js file?

Is there a way to access a variable defined in a JavaScript file from a Vue file and pass it to the Vue file? In the following code snippet, there is a template.js file and a contact.vue file. The template file converts MJML to HTML and saves the output to ...

There seems to be an issue with the location.href function in the server-side code of

I'm encountering an issue in the code below where I am attempting to redirect to the login page, but it seems to not be functioning as expected. app.get('/current-pass', (req, res) => { res.sendFile(path.join(staticPath, "currentPass ...

The multiArr.shift() operation is throwing a TypeError: The function shift cannot be located in the SN object

As a beginner in Java app development, I am currently attempting to export JSON from a Google spreadsheet. While watching a tutorial, I came across the following code: function doGet(){ var result ={}; var sheet1 = SpreadsheetApp.getActiveSpread ...

Utilizing various filters and sorting options on API response within Angular 8

Upon receiving the following API response: [ { "imgPaths":[ "gallery/products/55ccb60cddb4d9bded02accb26827ce4" ], "_id":"5f3e961d65c6d591ba04f3d3", "productName":" ...

Get ready for transitioning with a cell that is populated by JSON data

When populating a UITableViewCell with JSON data, I am using the following method: override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdent ...

How to transfer data from JavaScript to PHP using AJAX

After spending countless hours attempting to make this function properly, I have come to you for assistance :) I have created a PHP page that can exhibit files from a server. I am able to modify the files using an editor plugin, where the Textarea tag is ...

Exploring the possibilities of implementing the .map() function on a JSONArray within a ReactJS project using ES

When I receive a JSONArray from the server, my goal is to use .map() on it in order to extract key-value pairs of each object within the array. However, when I try to implement this code, I encounter an error stating "files.map is not a function". Can some ...

Filling in the fields based on the data in the JSON

I prefer not to rely on jQuery for this task. If possible, I would like to maintain the presence of <mytag>. The JSON data structure I am working with is as follows: { "datas": [ { "id": "hotel_name", "value": ...

swap = with u003d in c sharp

Trying to decode a base-64 string: oKQmwbpPwZGxUGeWQNBucVmNy1JVsxM9uNivn6hpkia+15y3yIemkW8GXW423krf8WNk6yebQixZW78EpPMMtzldQbbsaEmd4aUDCwp78ivOuh83nC8fHy2gwkm5NcS7aaGm2KxkUsWa5ouNUa7BUWPZ3F7LXFR/SLjZRTMY8u7hwYEQCmUQk/zNXsLyHHwZQiOjZfXdb1nC4vu1LItxaw== Tri ...

I encountered an issue in node.js where I was unable to delete a folder after renaming a zip

When attempting to rename an uploaded file using the code below: fs.rename('xxxxx','xxxxx',function(err) { }); I encountered an issue within the callback function. I attempted to remove a folder using the following code: fs.rename(& ...

Create an array using modern ES6 imports syntax

I am currently in the process of transitioning Node javascript code to typescript, necessitating a shift from using require() to import. Below is the initial javascript: const stuff = [ require("./elsewhere/part1"), require("./elsew ...

Finding the complete object based on its index

Hey there, I'm looking to access a specific object in my JSON data by using an index. Can anyone guide me on how to do this? Here's a snippet of my JSON data: [{ "rec": ["act1","act2","act3"], "rec2": ["act11","act23","act4"] }] I'm ai ...

Error message in Vuex4: Unable to access 'state' property because it is undefined

Having trouble with Vue3 and Vuex4, I keep encountering this error: Uncaught TypeError: Cannot read properties of undefined (reading 'state') at ReactiveEffect.eval [as fn] (App.vue?3dfd:36) at ReactiveEffect.run (reactivity.esm-bundler.j ...

What is the process to save all decoded information into a JSON file?

I am encountering an issue while trying to convert XML data into a JSON file. The problem arises when I attempt to write the marshaled data to the JSON file - it seems to only overwrite the existing data in the file, resulting in only the last XML element ...

Locate grandchildren elements using getElementById

My task is to modify the content and attributes of the table. The DOM structure is generated by a third-party tool, and I am using JavaScript to make changes in various sections. <div id="myId"> <div> <div> <table&g ...