Eliminate properties from a TypeScript interface object

After receiving a JSON response and storing it in MongoDB, I noticed that unnecessary fields are also being stored in the database. Is there a way to remove these unnecessary fields?

interface Test{
    name:string
};
const temp :Test = JSON.parse('{ "name":"someName","age":20 }') as Test;
console.log(temp);

Here is the output:

{ name: 'someName', age: 20 }

Answer №1

To extract specific properties from an object, you can utilize a function like the following:

function selectProperties<T, K extends keyof T>(obj: T, ...keys: K[]): Pick<T, K> {
    const selected = {} as Pick<T, K>;

    keys.forEach(key => selected[key] = obj[key]);

    return selected;
}

Subsequently:

let person = { "name": "John Doe", "age": 30 };
let selectedProps = selectProperties(person, "name") as SelectedResult;
console.log(selectedProps); // { name: "John Doe" }

Answer №2

Imagine having an object like this.

const obj = {name: "Alice", age: 30, city: "New York"};

To create a new object with just name and age, you can use this method.

const {city, ...newObj} = obj;
console.log(newObj);

You will notice that newObj now only contains name and age.
Moreover, there won't be any error if the field city doesn't exist in obj. For instance,

const obj: any = {name: "Bob", age: 25, country: "Canada"};
const {city, ...newObj} = obj;
console.log(newObj);

This code runs smoothly without errors, and if you check the value of city, it will be undefined.

Answer №3

If you wish to delete the age property:

temp = {...temp, age: undefined}

By executing this code snippet, you can successfully eradicate the age key from your object.

Answer №4

To ensure strong typing, one approach is to create a dummy object that adheres to your desired interface (

const ideal: IMyInterface = {field1: "value"};
). Then, when receiving objects, you can check their fields against Object.keys(ideal). This way, any changes made to the interface will trigger errors in this filtering code, preserving type integrity.

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

Is it possible to generate a "pop-up" window upon clicking on the register button?

As a backend programmer, I'm looking to create a popup window that appears in front of the current window when users click "register", eliminating the need for redirection to another page. I believe you understand the concept. How can I achieve this? ...

Total sum of elements in the JSON document

In R, I have imported a geojson file called routes, which consists of polylines. The nodes are nested within lists, creating a hierarchical structure. For instance: > routes$features$geometry.coordinates[100] [[1]] [,1] [,2] [1,] 73.8460 ...

Using j Query to create custom masks for various formats with the option to include optional digits

Looking for a way to mask the CVV card number..! The masking should allow for either 3 numbers like xxx 123 or 4 numbers like xxxx 4567 I have attempted to implement this with jQuery mask plugin, but it only allows for 4 characters. How can I enable both ...

Troubleshooting VueJS route naming issues

I am having an issue with named routes in my Vue app. Strangely, the same setup is working perfectly fine in another Vue project. When I click on a named router-link, the section just disappears. Upon inspecting the element in the browser, I noticed there ...

Looking to incorporate HTML and JavaScript to create two unique forms that can be submitted separately on a single webpage

If I can't find an answer, then I ask: There are two different forms on the page: one is the "ask for call" form (which appears on every page of the site) and the other is a simple "contact form" (specifically placed on the contact page). Both forms ...

Utilizing Objects as Properties in Phaser.Scene in Phaser 3

I've just started working with Phaser using TypeScript and I'm facing an issue. I attempted to move my main objects out of the create and preload methods by loading them as Phaser.Scene class properties. However, after making this change, my game ...

Encountering a blank webpage displaying a warning that reads, "The use of 'event.returnValue' is outdated

Although this issue has been discussed before and was previously considered a bug, I am currently using jQuery v1.11.0, which should have resolved it. The problem I am encountering is that when my page loads, there is supposed to be a slide-in effect (as a ...

Tips for showcasing JavaScript variables on a webpage

I am working with various JavaScript variables that involve displaying values inside div elements. goalDiv = "<div class=goal-parent id=goal-parent"+Id+">"+ "<div class=goal>"+ "<div class=top-layer>"+ "<div class=compone ...

Show additional information when a row in the Bootstrap Vue table is clicked

I am attempting to create a unique user experience by displaying row details when a row is clicked, rather than clicking on a button as described in the documentation. However, the documentation lacks specific instructions on how to implement this feature. ...

Population of the global namespace in JavaScript without the need for the 'new'

After watching the Douglas Crockford video on JavaScript, one thing that caught my attention was his explanation of what happens when you forget to use new for a class. He mentioned that doing so would populate the global namespace, which in the browser is ...

Combining two sets of elements in Java to form a Json using Jackson

Is there a way to combine two List of objects retrieved from the database into a single object in order to serialize with Jackson and deserialize in the view? ObjectMapper mapper = new ObjectMapper(); jsonTutorias = mapper.writeValueAsString(tuto ...

I am encountering an error when trying to fetch a JSON response from a PHP script, even though I am able

Below is the Javascript code I am using to initiate an AJAX call from a PHP file: $(document).ready(function(e) { $(function(){ $.ajax({ type:'GET', dataType: 'jsonp', data: { ...

Angular4 and jQuery working together for effective navigation and pagination

Trying to implement pagination in angular 4 and jQuery, but encountering an issue where clicking on the next button causes it to skip through multiple pages at once (2, then 3, then 5)... Component code: addClass(x) { $(".page-item").click(function () ...

Two liquid level divs within a container with a set height

I hesitated to ask this question at first because it seemed trivial, but after spending over 3 hours searching on stackoverflow and Google, I decided to give it a shot. The issue I'm facing can be found here: http://jsfiddle.net/RVPkm/7/ In the init ...

Determine the frequency of each element in an array and arrange them in ascending order

In my quest to locate occurrences of numbers within an array, I aimed to display the numbers and their respective frequencies in ascending order. Here is what I was trying to achieve: let arr = [9,-10,2,9,6,1,2,10,-8,-10,2,9,6,1]; // {'-10': 2, ...

Adding Jade template variable to an inline function

Trying to implement the JSCharts library. block content | <div id="chartcontainer">This is just a replacement in case Javascript is not available or used for SEO purposes</div> script. var myData=new Array() var myData = new Array([10 ...

Custom value in Field for radio type in Redux form

Can anyone help me figure out how to input text into a radio field using Redux form? Here are the fields I am working with: <Field name={some.name1} value={'text1'} component={renderRadioElement} type="radio" /> <Field name= ...

Learn how to implement a vertical bar chart in Highcharts by using it as a component and passing it as props

I recently imported a Bar Chart component from Highcharts, but it is being displayed horizontally. I would like to convert it into a vertical chart instead. Can someone please assist me in achieving this by passing the necessary props? <template v-slot ...

Failure to choose a value in AngularJS using the Chosen directive

I am currently developing a project with AngularJS and I need to display the selected value. To achieve this, I am utilizing the chosen filter available at: https://github.com/leocaseiro/angular-chosen Below is the code snippet that I have implemented: ...

Finding out if an array is empty or not in Reactjs: A Quick Guide

I am currently working with Reactjs and Nextjs. I am using axios to fetch data, and I need a way to determine if the array (students.data) is empty before running a map or loop. How can I achieve this? Here is the code snippet I am working with: const [stu ...