What is the process for deleting keys and values from a JSON object?

I am currently working with the Spring Framework and AngularJS in JavaScript. I have successfully made an AJAX request, but encountered an issue when trying to remove certain keys and values from the response data. Here is my code:

$.ajax({
    type: 'POST',       
    dataType: 'JSON',
    data:  JSON.stringify(search),
    contentType:"application/json; charset=UTF-8",
    url: '/yboard/select',
    error: function() {         
        alert("Loading failed!");
    },
    success: function(returnJSON) {     

        if (returnJSON.success) {           

            var result = JSON.stringify(returnJSON.items);
            console.log("no : " + result);      


        } else {
            alert("it's failed");                           
        }
    }
});

The output is:

no :     [{"boardID":"9b5199799c908e48051e2e131f2d35cc","no":204,"capital_stock":"","pno_stock":"3204000336","pname_stock":"HEATER","storage_code_stock":"C03","storage_name_stock":"A","price_indicator_stock":"M","unit_stock":"EA","stock_amount_stock":"12.00","tracking_no_stock":"015","standard_stock":"WATLOW: SFRE","client_code_stock":"1193","client_name_stock":"aaa","priority_stock":0},{"boardID":"6a11d21aa400ff6c94d7d7a21b762433","no":203,"capital_stock":"","pno_stock":"3204000328","pname_stock":"HEATER","storage_code_stock":"C03","storage_name_stock":"A","price_indicator_stock":"M","unit_stock":"EA","stock_amount_stock":"12.00","tracking_no_stock":"015","standard_stock":"SFRE","client_code_stock":"1153","client_name_stock":"bbb","priority_stock":0}]

I attempted to remove the 'boardID' and 'priority_stock' keys using the following code:

delete returnJSON.items['boardID']
delete returnJSON.items['priority_stock']

or

delete result['boardID']
delete result['priority_stock']

However, I was unsuccessful in removing them. What could be causing this issue?

Answer №1

To implement this functionality, you can utilize the ES6 Array's Map method along with Arrow function expression.

See the Code in Action

let returnJSON= {
"items": [{
"boardID": "9b5199799c908e48051e2e131f2d35cc",
"no": 204,
"capital_stock": "",
"pno_stock": "3204000336",
"pname_stock": "HEATER",
"storage_code_stock": "C03",
"storage_name_stock": "A",
"price_indicator_stock": "M",
"unit_stock": "EA",
"stock_amount_stock": "12.00",
"tracking_no_stock": "015",
"standard_stock": "WATLOW: SFRE",
"client_code_stock": "1193",
"client_name_stock": "aaa",
"priority_stock": 0
}, {
"boardID": "6a11d21aa400ff6c94d7d7a21b762433",
"no": 203,
"capital_stock": "",
"pno_stock": "3204000328",
"pname_stock": "HEATER",
"storage_code_stock": "C03",
"storage_name_stock": "A",
"price_indicator_stock": "M",
"unit_stock": "EA",
"stock_amount_stock": "12.00",
"tracking_no_stock": "015",
"standard_stock": "SFRE",
"client_code_stock": "1153",
"client_name_stock": "bbb",
"priority_stock": 0
}]
};

var res = returnJSON.items.map(obj => {
  (obj.hasOwnProperty('boardID')) ? delete obj.boardID : '';
  (obj.hasOwnProperty('priority_stock')) ? delete obj.priority_stock : '';
  return obj;
});

console.log(res);

Answer №2

The elements attribute within your responseJSON object is structured as an array. With two elements present, removing specific keys such as boardID and priority_stock requires iterating over each element individually to delete the desired keys:

for (let j = 0; j < responseJSON.elements.length; j++) {
     delete responseJSON.elements[j].boardID;
     delete responseJSON.elements[j].priority_stock;
}

Answer №3

Remove all keys related to items

returnJSON.items.forEach(function(x){ delete x['boardID'] });
returnJSON.items.forEach(function(x){ delete x['priority_stock'] });

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

Access any nested node within a JSON/JS object by specifying the key's value

After spending hours searching on various forums for a solution to my problem, I have yet to find one that directly addresses the issue I am facing. So, please take a moment to review the details below. The object structure in question is as follows: let ...

Cordova: Deciphering the significance of PACKAGE_NAME within android.json

We are currently working on a Cordova application that utilizes several plugins. We recently encountered an issue with our build, and while investigating a solution, I came across the android.json file in the plugins directory. Within this file, there is a ...

Using Jakson in Java to deserialize empty JSON values

Currently, I am utilizing Spring 4 MVC, JQDataTable, and the Jackson library to transmit a JSON object from a JSP page to a Spring controller. Within a table, when the save button is clicked, an AJAX call is triggered. There are two scenarios to consider: ...

Tips for resolving a 422 error on GitHub when attempting to create a repository using an Android device

After deleting an old repository, I attempted to create a new one which led to an error. I have been using my phone for a long time to delete and create repositories without any issues, so I'm not sure what changed today. I reached out to chat GPT fo ...

Webpack encounters difficulty resolving non-js `require`s located within node_modules

In my Next.js project, I have set up the configuration to handle imports ending in .web.js, which works fine except for files within the node_modules directory. For this setup, I adjusted the webpack config by setting resolve.extensions = ['.web.js&ap ...

Unable to prevent ordered lists from overlapping with other content I attempt to place beneath them in HTML

function filterImages() { let input = document.getElementById('searchbar').value; input = input.toLowerCase(); let images = document.getElementsByClassName('gallery'); for (let i = 0; i < images.length; i++) { ...

Collecting information from MySQL and transferring it to a Java application through a PHP script utilizing JSON

I am looking to develop a Java application that can retrieve data from MySQL and initially store it in a list, with the option of eventually storing it in a JTextArea. Currently, I have a database with tables on my localhost and a PHP script that fetches ...

Tips for notifying highlighted text in Kendo Editor

How can I provide an alert for a selected text inside the kendo editor? I have attempted the code below <textarea id="editor"></textarea> <script> $("#editor").kendoEditor(); var editor = $("#editor").data("kendoEditor"); var html = edit ...

Using the array.prototype.map method on props in React.js results in an array that is devoid

Recently, I've started exploring the world of React and encountered a problem while attempting to convert the value of props into a JSX element using array.prototype.map(). You can learn more about this method at this link. Here is a snippet of a Rea ...

How can I pass the dynamically generated ID from PHP to AJAX/jQuery using an anchor tag?

I'm seeking help with jQuery and Ajax as I am new to it. My issue is that I have multiple 'edit' buttons in a table, one for each row's data. When I click on an edit button to modify the data, they all open at once instead of just the s ...

Next.js - utilizing dynamic API routes within nested folders

Currently, I am working on developing a basic API that reads a local JSON file. My goal is to create a dynamic API that can adjust based on the specific calls it receives. Within my API folder structure, I have: api --book ---[id].js ----content -----[id ...

An error has occurred due to a connection timeout with the net.Socket

I have been attempting to send text to my network printer using a tcp connection. function print(buf2){ var printer = new net.Socket(); printer.connect(printer_port, printer_name, function() { console.log('Connected'); printe ...

Displaying JSON data in a popup window resembling a download prompt

I'm a beginner in front end development and facing difficulty in displaying JSON in a new window. Currently, I'm allowing users to download the JSON file like this var blob = new Blob([$scope.data], {type: 'json'}); ...

Is it possible to adjust the code for fs.readFileSync(__dirname + '/index.html);?

Is it possible to change the code from fs.readFileSync(__dirname + '/game.php'); to fs.readFileSync(__dirname + '/game.php?id='+id);? I encountered an error while trying to do so: fs.js:549 return binding.open(pathModule._makeLong( ...

Having trouble capturing user_id in my dashboard component - Laravel and Vue.js combination

I am facing an issue with extracting user_id from my dashboard Vue component TableEditLinks.vue. When I try to change user_id in the submitForm() method from "1" to "document.querySelector("meta[name='user_id']").content('content')", it ...

Unable to reach controller action with Ajax request

I've been encountering issues trying to make a Get request to hit the specified URL. Initially, I attempted inputting the URL parameter manually in a separate JS file, then transitioning all my JS to cshtml to test out Razor. However, I am still facin ...

Ways to store a filestream coming from Node.js into AngularJS

When using my express server, I have a post-request set up to retrieve a pdf file from Amazon S3 and then send it back to Angular. This is the endpoint in my express server: var fileStream = s3.getObject(options).createReadStream(); fileStream.pipe(res); ...

Working with Vuex: Simplifying state management by accessing multiple state objects with a single update mutation/action

I am facing a challenge with updating objects containing different strings using a single mutation and action in my project. Currently, I am attempting to extract a string from an input field's value and name, using the name as the object property to ...

What is the best way to mix up all the characters within the content of an HTML document?

<div id="contentContainer"> <h1>First Page</h1> <section id="mainSection"> <p>Lorem ipsum dolor sit amet</p> <ul> <li><a href="#">Black world</a></li> ...

Troubleshooting Spring's difficulty in locating resource files (css, jsp...)

Currently, I am integrating a jsp file as a model from a Controller and aiming to incorporate CSS styles and JS libraries into the project structure. Project Structure Webcontent assets WEB-INF jsp For the configuration in web.xml: <web-app versio ...