用javascript类转换对象

时间:2018-12-13 17:38:24

标签: javascript

我正在转换从API接收的数据。前端需要显示一些计算。

处理数据转换的正确方法是什么?

  • 我应该为要传递的对象定义一个属性吗?如果是这样,为什么
  • 这是使用setter和getter的好用例还是不必要?

const dogData = {
  dog_name: "filo",
  born_time: 1530983852,
  coat_color: "brown"
};

class Dog {
  constructor(data) {
    //do I need to set this.dog to the data object, what's the benefit of doing so?
    this.dog = data;

    this.name = this.dog.dog_name;
    // vs
    this.name = data.dog_name;

    //Should I use setters and getters?
    this.color = this.dog.coat_color;
    // vs
    this._color = this.dog.coat_color;

    this.age = this.calculateAge();
  }

  calculateAge() {
    return Date.now().getTime() - this.dog.born_time;
  }

  //Is this a good case where I  should using getters to access the properties or would that be superfluous?
  //should I be setting the properties with setters in this case?
  get color() {
    return this._color;
  }
}

const dog = new Dog(dogData)

3 个答案:

答案 0 :(得分:2)

您无需在班级中复制数据。

您可以直接分配类字段(使用object destructuring可以提高可读性)。

const data = {
  dog_name: 'filo',
  born_time: 1530983852,
  coat_color: 'brown'
}

class Dog {
  // Directly assign values
  constructor({ dog_name, born_time, coat_color }) {
    this.name = dog_name
    this.bornAt = born_time
    this.color = coat_color
  }

  // Getter for computed properties
  get age() {
    return Date.now() - this.bornAt
  }
}

const dog = new Dog(data)

仅计算属性(动态值或格式化值)需要字母。

好的例子:

class Person {
  constructor({ firstname, lastname }) {
    this.firstname = firstname
    this.lastname = lastname
  }

  get fullname() {
    return `${this.firstname} ${this.lastname}`
  }
}

答案 1 :(得分:0)

class Dog {
    constructor(data) {
        const {
            dog_name: name,
            born_time: age,
            coat_color: color
        } = data;
        Object.assign(this, {
            name,
            age,
            color
        });
    }
}

const dogData = {
    dog_name: "filo",
    born_time: 1530983852,
    coat_color: "brown"
};

const dog = new Dog(dogData);

console.log(dog.name);

答案 2 :(得分:0)

Q

  

尽管如此,我仍会抛出一种可能的只读方法吗? –彼得·塞利格(Peter Seliger)

A

  

这不会疼。我赞赏不同的方法。 –马修·莫兰(Matthew Moran)

...我们开始...

// module start ... e.g. file: "Dog.js"


// locally scoped helper function
function calculateAge(dateOfBirth) {
  return (Date.now() - dateOfBirth);
}

/*export default */class Dog {
  constructor(initialValue) {

    Object.defineProperties(this, {
      valueOf: { // just in order to hint what `initialValue` might still be good for.
        value: function () {
          return Object.assign({}, initialValue);
        }
      },
      name: {
        value: initialValue.dog_name,
        enumerable: true
      },
      color: {
        value: initialValue.coat_color,
        enumerable: true
      },
      age: {
        get() {
          return calculateAge(initialValue.born_time);
        },
        enumerable: true,
      }
    });
  }
}
// module end.


// test
const dogData = {
  dog_name: "filo",
  born_time: 1530983852,
  coat_color: "brown"
};

const dog = new Dog(dogData);

console.log('Object.keys(dog) : ', Object.keys(dog));
console.log('dog.valueOf() : ', dog.valueOf());

console.log('dog.age : ', dog.age);
console.log('dog.name : ', dog.name);
console.log('dog.color : ', dog.color);

console.log('(dog.age = 298146912) : ', (dog.age = 298146912) && dog.age);
console.log('(dog.name = "spot") : ', (dog.name = "spot") && dog.name);
console.log('(dog.color = "black") : ', (dog.color = "black") && dog.color);
.as-console-wrapper { max-height: 100%!important; top: 0; }