Remove properties that are not part of a specific Class

Is there a way to remove unnecessary properties from the Car class?

class Car {
    wheels: number;
    model: string;
}

const obj = {wheels:4, model: 'foo', unwanted1: 'bar', unwantedn: 'kuk'};

const goodCar = filterUnwantedProps(obj); // goodCar only contains fields wheels and model

What is the best method to keep only the existing fields of the Car class in obj?

Answer №1

To filter out unwanted properties from an object, you can utilize the reduce() method with keys of a new instance of the Car class.

class Car {
  constructor() {
    this.engine = 'V8';
    this.color = 'red';
  }
}

const vehicle = {
  engine: 'V6',
  color: 'blue',
  type: 'SUV',
};

var filteredVehicle = Object.keys(new Car)
  .reduce(function(result, key) {
    if (key in vehicle) result[key] = vehicle[key];
    return result;
  }, {});

console.log(filteredVehicle)

Answer №2

To simplify the process, you can utilize a constructor:

class Vehicle {
  constructor(tires, make) {
    this.tires = tires;
    this.make = make;
  }
}

const obj = {tires:4, make: 'Toyota', unwanted1: 'red', unwantedn: 'blue'};

const newVehicle = new Vehicle(obj.tires, obj.make);

console.log(newVehicle);

Alternatively, you can also structure it like this:

class Vehicle {
  constructor(obj) {
    this.tires = obj.tires;
    this.make = obj.make;
  }
}

const obj = {tires:4, make: 'Toyota', unwanted1: 'red', unwantedn: 'blue'};

const newVehicle = new Vehicle(obj);

console.log(newVehicle);

Answer №3

Another technique that can be considered is utilizing object destructuring and returning the specified object from the function:

const filterUnwantedProps = function({
  wheels: wheels,
  model: model
}) {
  return {
    wheels: wheels,
    model: model
  }
};

Here's a snippet of code showcasing this method in action:

class Car {
  wheels: number;
  model: string;
};

const obj = {
  wheels: 4,
  model: 'foo',
  unwanted1: 'bar',
  unwantedn: 'kuk'
};

const filterUnwantedProps = function({
  wheels: wheels,
  model: model
}) {
  return {
    wheels: wheels,
    model: model
  }
};
const goodCar = filterUnwantedProps(obj);
console.log(goodCar);

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

The .val() function in jQuery can sometimes give different results when used on input elements with placeholder text in Firefox compared to Chrome

After analyzing the given HTML code, I've noticed discrepancies in the values returned by jQuery in Firefox and Chrome: HTML: <input type="text" name="name" id="name" placeholder="Type Here"> <input type="email" name="email" id="email" plac ...

Sending a parameter to the load method of the Selectize jQuery extension

I have a question about using the Selectize jQuery plugin for a dropdown box. I am not very familiar with jQuery, so please bear with me if this is a simple issue. I am making an ajax call to fetch data for the dropdown, but I need to pass a variable to th ...

Using JavaScript to control the state of a button: enable or

In the process of creating a basic HTML application to collect customer information and store it in a database, I have encountered a specific user interface challenge. Once the user logs into their profile, they should see three buttons. Button 1 = Print ...

TypeScript generic types allow you to create reusable components that

function genericIdentity<T>(arg: T): T { return arg; } let myGenericIdentity: <U>(arg: U) => U = genericIdentity; I see that the 'genericIdentity' function is accepting an argument of a generic type. However, I am unsure about ...

Tips on avoiding quotation marks in a Less variable containing a color identifier

I'm currently working on an HTML/CSS project where I aim to establish classes for labels and texts based on their color. For instance: .text-red{ color: red; } .label-white{ color: white; } In order to achieve this, my approach involves cr ...

How to successfully transfer input data from a dialog to a controller using jQuery and Grails

As a newcomer to Grails and jQuery, I recently created a jQuery dialog following this example: http://jqueryui.com/dialog/#modal-form The goal is to open a dialog, input data, and have it displayed in a dynamic table on the main page. Once all entries are ...

Tips for displaying a modal to a user only once

I've developed a Flask application that enables multiple users to register and log in. To achieve this, I have incorporated sessions into my code. When new users land on the initial page, they are greeted with a modal introducing them to the platform. ...

Execute a function on every item within a loop by utilizing jQuery

My view-model includes a data grid similar to the one displayed below <table> @foreach (var item in Model) //for(int i=0;i<Model.Count();i++) { using (Html.BeginForm("Edi ...

Leverage the power of Vue Nuxt Auth to activate authentication middleware on a route-by-route

Is there a way to implement auth middleware for individual routes using Class Components? How can I achieve the same functionality as this: <script> export default { middleware: 'auth' } </script> The following method does n ...

A Guide to Modifying Background Image Attribute using JavaScript

I am currently in the process of changing an attribute of a JavaScript variable from url("../images/video.png") (as declared in the CSS) to url("../images/pause.png") using this line of code: fullscreenPlayPauseButton.style.backgroundImage = "url("../imag ...

Leverage JSON files for pagination in NextJS

I am currently developing a science website where the post URLs are stored in a static JSON file. ScienceTopics.json- [ { "Subject": "Mathematics", "chapters": "mathematics", "contentList": [ ...

Tips for showing both label and value on a pie slice in Apex charts

I am currently utilizing apex chart within an angular application to showcase charts. I am specifically focusing on a pie chart and aiming to customize it by displaying labels on the values within each slice of the pie, similar to what is shown in the atta ...

What role does NPM play in the deployment of a Node.js App with AWS Beanstalk?

I'm interested in the workflow of an AWS Beanstalk deployment, particularly regarding the installation of packages. I assume that npm is used during the process to install packages on the server(s). However, I am curious to know if AWS Beanstalk utili ...

What steps should I take in order to correctly implement the onChange event and retrieve the event.target.value in my

Incorporating useForm, yupResolver, and Yup for validation caused issues with the previously functioning handleChange function. The value variable doesn't log anything when console.logged, indicating a disconnect with the input field content. Addition ...

Using Laravel and AJAX to save multiple selected filters for future use

I've been struggling with this issue for a few weeks now and just can't seem to wrap my head around it. On my webpage, I've implemented four filters: a search filter, a year filter, a launch-site filter, and a country filter. Each of these ...

Establishing a Geolocation Object in HTML5

My HTML5 app relies on Geolocation. In cases where the user denies permission for geolocation, I want to pass a default position object (latitude:0, longitude:0) to ensure the app can still function. I understand how to detect permission denial, but I&apo ...

Ways to transfer a value from a JavaScript file to a PHP file?

Is there a way to transfer data from a JavaScript file to a PHP file? Code: var year = (year != null) ? year : '".$this->arrToday["year"]."'; var month = (month != null) ? month : '".$this->ConvertToDecimal($this>arrTod ...

Retrieve the ActiveTabIndex value from an Ajax TabContainer using Javascript

Is there a way to retrieve the ActiveTabIndex from TabContainer when a tab is selected by the user? I've attempted the following approach without success. <script type="text/javascript"> function GetActiveTabIndex() { var tc = docum ...

Guidelines for implementing a vuex getter within the onMounted hook in Vue

Currently, my process involves fetching data from a database and storing it in vuex. I am able to retrieve the data using a getter in the setup method, but I would like to manipulate some of that data before the page is rendered, ideally in the onMounted m ...

Highlighting table rows when hovering in IE with JQuery - compatibility across all versions

I have a table on my jsp page with multiple rows and columns. I want to ensure that visitors can easily follow along when they interact with the table - by highlighting the row or column they hover over with a different background color. Although the **hov ...