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

I'm curious if anyone has had success utilizing react-testing-library to effectively test change events on a draftJS Editor component

​I'm having trouble with the fireEvent.change() method. When I try to use it, I get an error saying there are no setters on the element. After that, I attempted using aria selectors instead. const DraftEditor = getByRole('textbox') Draf ...

Guide to locating and substituting two integer values within a string using JavaScript

Given a string such as: "Total duration: 5 days and 10 hours", where there are always two integers in the order of days and then hours. If I need to update the old string based on calculations using fields and other values, what is the most efficient meth ...

increase the selected date in an Angular datepicker by 10 days

I have a datepicker value in the following format: `Fri Mar 01 2021 00:00:00 GMT+0530 (India Standard Time)` My goal is to add 60 days to this date. After performing the addition, the updated value appears as: `Fri Apr 29 2021 00:00:00 GMT+0530 (India St ...

Is it true that Javascript does not allow for saving or outputting actions?

After coming across this question, I discovered a way to extract a specific element from a Google translate page using Javascript. However, I also learned that it is nearly impossible to directly save something to the clipboard in Javascript without user i ...

What is the best way to pass my request data to my $scope variable?

I'm currently facing a challenge with this particular topic. My goal is to add the response data that I retrieve from Express to my angular $scope and then direct the user to their profile page. This is how my Controller Function is structured: $sc ...

TypeScript enum type encompassing all potential values

One thing I have learned is that keyof typeof <enum> will give us a type containing all the possible keys of an enum. For example, if we have enum Season{ WINTER = 'winter', SPRING = 'spring', SUMMER = 'summer', AUT ...

Exploring the contrast between Vuex store WATCH and SUBSCRIBE

Can you explain the main distinction between watch and subscribe, and when it is most appropriate to use one over the other? According to information on the Vuex official documentation, both methods appear to be essentially identical in functionality and p ...

What is the rationale behind requiring a semicolon specifically for IE11 in this function?

Currently, I am tackling some vuejs code to ensure compatibility with IE 11. Struggling with a persistent expected semicolon error in this particular function: chemicalFilters: function (chemical) { var max = 0; var min = 100; for (var ...

I am experiencing issues with the search feature in angular and node.js that is not functioning properly

Need assistance with debugging this code. I am currently working on adding search functionality to my Angular web page. However, when testing the code in Postman, I keep receiving the message "NO USER FOUND WITH USERNAME: undefined". Additionally, on the w ...

Creating an event on the containing element

Here is my HTML tag: <ul> <li> <form>...</form> <div> <div class="A"></div> <div class="B"><img class="wantToShow"></div> </div> ...

Ensure that you patiently wait for the axios method to finish execution before moving on to the

I am currently learning vue.js and struggling with the concept of promises. I need to initialize a variable with data from an API call, but I want to ensure that the Axios call is generic: { data: { list: [], }, methods: { ShowList: function ...

Triggering multiple subscription functions in Ionic 3 NGRX when a single state change occurs

I have developed an Ionic 3 application that utilizes NGRX for state management purposes. The app is designed to connect to a device via BLE technology. Within my connection page, where the BLE device is connected, I have implemented the following code: ...

Attempting to sort through elements in JavaScript

I'm looking to filter specific films based on choices made in the dropdown menus below. <select id="filmDropdown"> <option value="0">All Films</option> <option value="1">Film 1</option> <option ...

What could be the reason my component is not displaying the ContentChild associated with a directive?

It appears that utilizing a directive to target a content child from another directive is the recommended approach (source). However, why isn't my component able to recognize the component marked with the directive? ./my.component.ts import { Comp ...

Interact with the horizontal click and drag scroller to navigate through various sections effortlessly, each designed to assist you

Currently, I am facing an issue with my horizontal scrolling feature in JavaScript. It works perfectly for one specific section that has a particular classname, but it fails to replicate the same effects for other sections that share the same classname. ...

Leverage predefined JavaScript functions within an Angular template

I have been attempting to execute an eval function within my angular template in the following manner: <div *ngFor="..."> <div *ngIf="eval('...')"></div> </div> You understand what I'm trying to ...

The issue I am facing is that the map function is not functioning correctly when I click

I am currently working on a project in ReactJs that includes a sidebar with dropdown menu functionality. Desired Outcome When I click on an option in the sidebar that has a submenu, it should display that submenu and close upon another click. Curr ...

When utilizing Javascript's Array.push method, a nested array is generated that is inaccessible using the index

I have reviewed several articles discussing the issue of asynchronous calls returning undefined. Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference Get data from fs.readFile However, none of these articles ...

The display/block feature will only function if the div element is contained within a table

I am facing an issue with hiding/showing two div elements alternatively. The code works perfectly when the divs are placed within a table, but fails when they are not in a table due to compatibility issues with Internet Explorer. I prefer not to use a tabl ...

I encountered a PrimeVue error while running a Vue Jest test

When working on a Vue jest test, I encountered an error message "No PrimeVue Confirmation provided!" which seemed to be related to the useToast() and useConfirm() services. "transformIgnorePatterns": [ "<rootDir>/node_modules/(?! ...