0

I currently have a problem changing a detailed model to a less detailed update model when I have more data than expected in an object. Despite Typescript it can be that my backend sends me more data than I expect in my model and then also send back too much data, because I don't know of certain properties that they exist.

Let me give you a small example:
CarModel

  • manufacturer
  • model
  • color

UpdateCarModel

  • color

Recived Object from Backend:

  • manufacturer
  • model
  • color
  • yearOfConstruction

Here's my current code, which doesnt detect and remove the additional propery:

import { merge as lodashMerge } from 'lodash';

public static buildFromCarModel(car: CarModel): UpdateCarModel {
  let clone = lodashMerge(new UpdateCarModel(), car);
  delete clone.manufacturer;
  delete clone.model;

  return clone;
}

The problem is now that the backend expects an update model that only contains the color, but implicitly the year of construction has also been dragged through the code. Is there a way to give the object a model as a kind of template and keep only the properties that are in my expected model?


EDIT: The solution proposed in the marked duplicate is difficult for me to use because I have to specify all properties and additionally all methods, I would prefer a solution that only reads and transmits the properties, but not the functions

JohnDizzle
  • 1,268
  • 3
  • 24
  • 51
  • Possible duplicate of [How to get a subset of a javascript object's properties](https://stackoverflow.com/questions/17781472/how-to-get-a-subset-of-a-javascript-objects-properties) – str Jun 21 '18 at 07:50

1 Answers1

0

If I understood your question right. Then, following may be something that you want. Please note, you have to modify this as per your need.

let requiredCar = {
  color: null
}

let car = {
  color: 'red',
  other: 'properties'
}

function map(model, requiredModel) {
  var retObj = {};
  Object.getOwnPropertyNames(requiredModel).forEach(key => {
    retObj[key] = model[key];
  })
  return retObj;
}

console.log(map(car, requiredCar));
Vipin Kumar
  • 6,441
  • 1
  • 19
  • 25
  • I would prefer to have a general function to which I can pass an object and a model as a template instead of changing the constructor. I have models with more than just 3 attributes and also several models that have to be transferred to other models, the solution with constructors does not seem to me to be practicable for that. – JohnDizzle Jun 21 '18 at 07:56
  • Answer Modified. – Vipin Kumar Jun 21 '18 at 08:01