Ways to exclude an object field in Angular 7

Is there a way in Angular to exclude specific fields before making an http call, similar to the @JsonIgnore annotation in Java?

For instance:

Given this object:

{id: 1, libelle: 'test', mustIgnore: 'test'}
;

I am looking to have it transformed into: {id: 1, libelle: 'test'};

I attempted to use delete object.field, but I'm seeking a more streamlined approach, possibly through annotating my object.

Managing this manually for each object is challenging, especially when dealing with arrays of objects.

UPDATE :

I want to avoid deleting fields individually for every object. Is there a method to specify which fields should be excluded and have it done automatically whenever there's a different object with varying fields to remove?

Answer №1

Employing ES6 object destructuring allows for obtaining an immutable object excluding a desired property.

const obj = {id: 1, libelle: 'test', mustIgnore: 'test'};

// Destructure to separate mustIgnore and rest properties
const { mustIgnore, ...rest } = obj;

const projectedObject = rest;
 
console.log("old", obj);
console.log("new", projectedObject);

Answer №2

If you're dealing with an array, a simple way to transform it is by using the map method like this:

const ignoreArray = array
    .map(
        a => ({ id: a.id, label: a.label })
    )

This will give you a new array containing objects with only the id and label properties.

UPDATE: After considering Kunal's suggestion, a more efficient approach would be:

const ignoreArray = array
    .map(
        obj => {
            const { shouldIgnore1, shouldIgnore2, ...remaining } = obj;
            return remaining;
        }
    )

In this scenario, shouldIgnore1, shouldIgnore2, etc. represent the fields that should be omitted from the final result

Answer №3

In situations where your dataset is comprised solely of key+value pairings, a strategy to consider involves initiating an empty object {} and iteratively cycling through all entries within the initial object using a for loop. During this process, you can cross-reference each key against a designated array containing names of keys that should be excluded. If a specific item is found in the exclusion array, it can be bypassed; otherwise, it should be included in the new object being constructed.

Answer №4

const array = [
{id: 1, libelle: 'test1', mustIgnore: 'ignore1'},
{id: 2, libelle: 'test2', mustIgnore: 'ignore2'},
{id: 3, libelle: 'test3', mustIgnore: 'ignore3'}
];


const freshArray = [];

for (item of array) {
    const { mustIgnore, ...others } = item;
    freshArray.push(others);
}

console.log(freshArray);

 

Another approach:

const array = [
{id: 1, libelle: 'test1', mustIgnore: 'ignore1'},
{id: 2, libelle: 'test2', mustIgnore: 'ignore2'},
{id: 3, libelle: 'test3', mustIgnore: 'ignore3'}
];

const newArray = array.map(obj => {
                const { mustIgnore, ...rest } = obj;
                return rest;
 });


 console.log(newArray);

For more information, please refer to object destructuring, but this covers the basics!

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

Utilizing the default event object in ag-Grid's event methods with JavaScript

I am a newcomer to ag-grid and I need help with calling event.preventDefault() in the "cellEditingStopped" grid event. Unfortunately, I am struggling to pass the default JavaScript event object into it. Is there a way to make this work? Additionally, I al ...

What are the specified actions with Angular and p-picklist?

I have a situation with my angular code where I am displaying 2 lists and allowing items to be moved between them. I am looking for a way to trigger a method only when an item is moved from the available list to the selected list. I attempted to use (cli ...

Exploring the intricacies of JSON data in AngularJS

I am new to AngularJS and familiar with working with basic JSON data using AngularJS. I have complex JSON data that I need to work with. [ { "activity_user": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="09687a6d ...

The creation of a parameterized function that doubles as an object property

interface item { first: string; last: string; } const itemList = Item[]; updateAttribute = (index, attributeToUpdate) => { itemList[index].attributeToUpdate = "New first/last" } The snippet above showcases an interface named item with propertie ...

Defining JSON Schema for an array containing tuples

Any assistance is greatly appreciated. I'm a newcomer to JSON and JSON schema. I attempted to create a JSON schema for an array of tuples but it's not validating multiple records like a loop for all similar types of tuples. Below is a JSON sampl ...

There was an unexpected error: The development server's address information is not defined

Whenever I attempt to utilize ng serve with SSL and a custom hostname, I encounter the error message "An unhandled exception occurred: Dev-server address info is not defined." Has anyone found a solution to this issue? Here is the command I am using: ng s ...

xamarin.forms - Newtonsoft.Json.JsonSerializationException: Value conversion error occurred

As someone who is new to Xamarin.Forms, I've been working on deserializing a JSON string in order to display it in a listview. I managed to retrieve the JSON string from the server successfully, but encountered an error during deserialization: Newton ...

Struggling to successfully pass a function as an argument to the setTimeout method within an array in node.js using TypeScript

Here is an example that successfully demonstrates a function being called using setTimeout: function displayMessage(msg: string){ console.log(msg); } setTimeout(displayMessage, 1000, ["Hi!"]; After one second, it will print out "Hi!" to the console. ...

configure the environment variable NODE_ENV in a NodeJS application

I am trying to properly set process.env.NODE_ENV to 'production' in my local NestJS code. Here are the steps I have attempted: Added NODE_ENV=production to the serve script in package.json Added nx build --prod to the build script in package.jso ...

Troubleshooting problem with refreshing URL on "ionic serve" mode

After transitioning my project from Ionic 2 to Ionic 3, I've encountered an issue with ionic serve and the rebuilding process. Initially, when I build the project, everything functions as expected. However, I've noticed that the URL in the brows ...

Access your Angular 2 application on an external device during the development process

Is there a way to view your app in an external device like a cell phone web browser, instead of just running npm start and viewing it in your desktop browser? ...

Using Powershell to Transform JSON Data into Property Format

I'm currently facing a challenge that I am struggling to overcome due to my lack of experience. Any assistance from the experts on this platform would be immensely helpful :) My task involves converting JSON input into property format. For example: T ...

Incorporate an interface for handling potential null values using Typescript

Currently, I am utilizing Express, Typescript, and the MongoDB Node.js driver to develop my API. However, I am encountering an issue with the findOne method as it returns a promise that resolves with either an object containing the first document matching ...

Creating JSON values using double as the data type

I am in the process of creating a Json schema file that my C# code will use to validate Json files. One of the properties I have defined looks like this: "XOSCLockTime": { "type": "double" } Everyth ...

Obtaining a String from a nested Array within an Array using Swift

When trying to extract a String from an Array by iterating through it, I am encountering an issue. let parsed = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.AllowFragments) for item in parsed as! [Dictionary& ...

Leverage the power of React, Material-UI, and Typescript to inherit button props and incorporate a variety of unique

Looking to enhance the Material-UI button with additional variants like "square." How can I create a prop interface to merge/inherit props? Check out the following code snippet: import React from "react"; import { Button as MuiButton } from "@material-u ...

Issues encountered while implementing a wrapper service for PrimeNG's MessageService in Angular 8

I have developed a custom wrapper service for the MessageService provided by PrimeNG, rather than directly calling the add() method within the application. However, I am facing an issue where the code is not functioning as expected and no compile-time or r ...

Angular model-based forms encounter an issue with converting null to an object during asynchronous validation

In my Angular app, I'm working on implementing async validation for a model-based form. I've simplified the form by removing other fields for clarity, but there are additional fields in the actual form. The goal is to check if a username is uniqu ...

jqGrid JSON Parsing Issue

While utilizing jqGrid and JSON server responses, I am facing an issue with correctly mapping my JSON data. For instance, the server response appears as follows: [ {ID: 'cmp1', Name: 'Name1', Address: 'Address1', Phone: ...

Utilizing Jest and nest.js for testing with absolute paths

Looking at my jest configuration inside the package.json: "jest": { "moduleFileExtensions": [ "js", "json", "ts" ], "moduleDirectories":["node_modules", "src" ...