Reputation: 17364
I have a prototype
class Animal() {
constructor(name, weight) {
this.name = name
this.weight = weight
}
}
and some coming object, which contains these properties plus something else
const obj = {
name: "name",
weight: 5,
someRedundantProp: "bla"
}
I really enjoy JS mapping with Object.assign which would generically create an object for me with all properties, but here I want to fill this new object only with essential fields. Surely, I can map this object like
new Animal(obj.name, obj.weight)
but if at some point I would introduce new properties I will have to change code here, what I don't want to.
Is there some better way?
Upvotes: 2
Views: 4620
Reputation: 8921
This should work for you:
class Animal {
constructor(obj) {
const defaultFields = {
name: "",
weight: 0
}
Object.keys(defaultFields).forEach(key => defaultFields[key] = obj[key]);
Object.assign(this, defaultFields);
}
}
Upvotes: 1
Reputation: 7575
You could check if the first argument is an object and then assign the object to this.
But be warned, this has some nasty side effects too.
class Animal {
constructor( obj ) {
// Create an object that holds all available options
const defaultOptions = {
name: '',
weight: 0,
};
// Go over all available options
Object.keys( defaultOptions ).forEach( key => {
// Check if obj has key, otherwise use default option
this[ key ] = obj[ key ] || defaultOptions[ key ];
} );
}
}
const obj = {
name: "name",
weight: 5,
someRedundantProp: "bla"
}
const a = new Animal( obj );
console.log( a );
Upvotes: 1
Reputation: 17364
I came to this solution for now
let animal = new Animal()
Object.keys(animal).forEach(field => animal[field] = obj[field])
Upvotes: 0