简体   繁体   English

用期望的属性填充Javascript中的对象

[英]Fill object in Javascript with expected properties

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. 我真的很喜欢Object.assign的 JS映射,它将为我创建具有所有属性的对象,但是在这里,我只想用必填字段填充这个新对象。 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? 有更好的办法吗?

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);
    }
}

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 ); 

I came to this solution for now 我现在来到这个解决方案

let animal = new Animal()
Object.keys(animal).forEach(field => animal[field] = obj[field])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM