Delete a key-value pair from a JSON object in Angular

I need to manipulate a JSON response by removing specific object key values and storing the edited response separately for later use. While I know how to do this in simple JavaScript, I am unfamiliar with how to achieve this using AngularJS.

Json response

{
    "$id": "1",
    "XYZ": [],
    "ABC": [
        {
            "$id": "41",
            "ID": 1,
            "Order": 0,
            "Delay": 0,
            "Name": "abc",
            "Count": "9",
            "Storage": 3,
            "Groups": []
        }
    ],
    "Projected": 2019
}

I want to filter out the following key values from this JSON file:

"$id": "41","ID": 1,"Order": 0, "Delay": 0, "Groups": [], "Name": "abc"

The structure of the new JSON that I wish to store should be:

{
    "$id": "1",
    "XYZ": [],
    "ABC": [
        {
            "Count": "9",
            "Storage": 3
        }
    ],
    "Projected": 2019
}

Is there a method to achieve this using AngularJS?

Answer №1

Forget about fancy angular tricks, plain old JavaScript will do the job just fine. My method goes through each item in the ABC array and removes all properties specified in the props array. Keep in mind that this actively alters the properties of the ABC array items.

const obj = {
    "$id": "1",
    "XYZ": [],
    "ABC": [
        {
            "$id": "41",
            "ID": 1,
            "Order": 0,
            "Delay": 0,
            "Name": "abc",
            "Count": "9",
            "Storage": 3,
            "Groups": []
        }
    ],
    "Projected": 2019
}

// Now I want to filter out certain properties from this JSON object

const props = ["$id", "ID", "Order", "Delay", "Groups", "Name"];
props.forEach(prop => {
    obj.ABC.forEach(abc => {
      delete abc[prop];
    });
});

console.log(obj);

Answer №2

This approach offers a different solution compared to others. Let's assume we have a variable named json. The following method is straightforward and effective.

let length = json.ABC.length;
for (let index=0; index<length; index++){
    delete json.ABC[index].$id;
    delete json.ABC[index].ID;
    delete json.ABC[index].Order;
    delete json.ABC[index].Delay;
    delete json.ABC[index].Groups;
    delete json.ABC[index].Name;
}

Answer №3

Give this code a try:

let data = {
    "$id": "1",
    "XYZ": [],
    "ABC": [
        {
            "$id": "41",
            "ID": 1,
            "Order": 0,
            "Delay": 0,
            "Name": "abc",
            "Count": "9",
            "Storage": 3,
            "Groups": []
        }
    ],
    "Projected": 2019
};

data["ABC"] = data["ABC"].map(obj => ({
  "Count": obj["Count"],
  "Storage": obj["Storage"]
}));
// or in a dynamic way
let keysToKeep = ["Storage", "Count"];
data["ABC"] = data["ABC"].map(obj => {
  let newObj = {};
   keysToKeep.forEach(key => newObj[key] = obj[key]);
  return newObj;
});
console.log(data)

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

Altering iframe Content with the Help of Selenium Web Driver

I am looking to update the content of an iframe with new material using Selenium WebDriver. Note: I have attempted the following method: driver.swithTo().frame(frame_webelement); driver.findElement(By.xxx).sendKeys("Mycontent"); While I was able to cle ...

When attempting to run HTML and JavaScript files locally, an error is encountered: "TypeError: The module name 'openai' is not resolving to a valid URL."

As a beginner in web development, I decided to follow a tutorial on creating a web application using the OpenAI API. The tutorial instructor runs the code in an environment called Scrimba, but I am working on my MacBook. This is how the app functions: it ...

Tips for allowing divs to be dragged and resized within table cells and rows

UPDATE I believe that utilizing Jquery is the most appropriate solution for resolving my issue with the demo. Your assistance in making it work would be greatly appreciated. Thank you. My goal is to develop a scheduler application. https://i.sstatic.net ...

"Looking for a way to eliminate the background of an image on NextJS? Learn

https://i.stack.imgur.com/zAsrJ.png When this image is incorporated into a Nextjs rendering, it unexpectedly includes additional content. <div className="flex flex-col items-start justify-start rounded-3xl p-4 bg-boxi w-1/3"> <div cla ...

Drawing the canvas is taking place prior to the image being fully loaded in JavaScript

Currently, I am in the process of creating a collage using images that are all sized at 174x174 pixels. The images are stored on my server, and while my program can locate them successfully, it requires me to click the "save image" button twice for them to ...

PhpStorm alerts users to potential issues with Object methods within Vue components when TypeScript is being utilized

When building Vue components with TypeScript (using the lang="ts" attribute in the script tag), there is a warning in PhpStorm (version 2021.2.2) that flags any methods from the native JavaScript Object as "Unresolved function or method". For exa ...

Issue arises when the value becomes nonexistent following the execution of a

Having an issue with my code where I have one class with a function in it, and another class that imports the first class to use that function. However, after the function is executed, I am not getting the expected value. First class: export class MoveE ...

What is the best method for accessing OpenWeatherMap details via JSON?

I am facing a challenge in JavaScript as I attempt to create a program that fetches weather information from OpenWeatherMap using JSON. My experience with JSON is limited, but I believe I have a grasp of the underlying concepts. Despite this, when I trigge ...

Error: Headers cannot be set after they have already been sent, resulting in an Unhandled Promise Rejection with rejection id 2

I'm a beginner with Node.js and I've been using express.js. In a section of my code, I'm trying to retrieve data from a form via AJAX and store it in a variable called url. I have access to request.body, but I'm encountering an issue wh ...

Managing ng-show in AngularJS outside the ng-repeat loop

Currently, I am diving into the world of Angular and experimenting with toggling the visibility of content div based on clicks on side menu items. <div id="side-menu"> <h3>Side Menu</h3> <div ng-repeat="item in example"> &l ...

Having difficulty changing the visibility of a div with Javascript

I've developed a piece of vanilla JavaScript to toggle the visibility of certain divs based on the field value within them. However, I'm encountering an issue where trying to unhide these divs using getElementById is resulting in null values. D ...

What steps can I take to make sure the JavaScript runs and updates the images correctly?

Trying to adjust image sizes with JavaScript. Followed a jsfiddle example, but it's not working on the page. Seems like the script is misplaced. How can I fix this? <!DOCTYPE html> <html> <head> <meta http-equiv="cont ...

ngTable select all data that has been filtered

I have encountered an issue with selecting only the rows from an ng-table that have been filtered. The current code filters the table rows successfully, but it also selects rows that are not displayed: Controller: let sampleData = [{id: 1, name: 'Jo ...

Issue with AngularJS viewContentLoaded not being triggered during page refresh and initial load when utilizing a directive

There seems to be some irregularities occurring when utilizing a custom directive and relying on the viewContentLoaded event to execute... Here is a simplified version of the issue: var myApp = angular.module('myApp',[]); myApp.directive(&apos ...

Utilizing Jquery to Pass an Optional Function to Another Function

I am currently working on a function that utilizes AJAX to submit data and then displays a dialog indicating whether the process was successful or not. Everything seems to be functioning smoothly, but I now want to add the capability of passing an addition ...

Steps to transforming a standard array into a multidimensional array

I have a JSON array that is generated after submitting a form using the formSerialize function. Here is an example of how the array looks: [ {"name":"client_management-testmonitoring","value":"0"}, {"name":"client_operations-testmonitoring","v ...

Exploring date comparison in AngularJS

I've encountered an issue while using ng-show in a page that I'm currently designing: <td ng-show="week.EndDate > controller.currentDate"> The week object has a property called EndDate, and the value of currentDate is being set in my c ...

Increase value by 1 with the push of a button within two specified ranges using JavaScript

I am looking to create buttons that will increase the value of both the first and second range by 1 when pressed, as well as decrease the value of both ranges by 1 when pressed. Here is my code: function run(){ var one = document.getElementById("rang ...

Error occurs during server to server mutation with Apollo Client (query successful)

Currently, I am using apollo-client on my web server to interact with my graphql server (which is also apollo). While I have successfully implemented a query that retrieves data correctly, I encounter new ApolloError messages when attempting a mutation. Od ...

Uploading to a designated folder using Google Script

Looking to create a form for uploading files, photos, and videos to specific folders in Google Drive using Google Apps Script. However, encountering an error "invalid argument listener". Here is the HTML index: <!DOCTYPE html> <html> &l ...