写了个 json 转 class 的小工具(轻喷)

2020-07-26 13:11:45 +08:00
 scuuzqc

作为前端,由于自己对代码变量有洁癖~~只用驼峰,看不得下划线和驼峰混用,看着揪心。

所以对于后端发过来的各种乱七八糟的变量,比如单字母,下划线变量,还有一些奇怪的数据(加密,二进制等),对于老接口,并不是接口协商能解决的,写了个小工具,算比较优雅的解决了~~

用法:

import { property, toClass, toPlain } from 'class-convert';
 
class UserModel {
  @property('i')
  id: number;
 
  @property()
  name: string;
}
 
const userRaw = {
  i: 1234,
  name: 'name',
};
 
// use toClass to convert plain object to class
const userModel = toClass(userRaw, UserModel);
// you will get a class, just like below one
{
  id: 1234,
  name: 'name',
}

const userModel = {
  id: 1234,
  name: 'name',
};
// use toPlain to convert plain object to class
const userRaw = toPlain(userModel, UserModel);
// you will get a class, just like below one
{
  i: 1234,
  name: 'name',
}

支持双向转换~ 详情请参阅: https://www.npmjs.com/package/class-converter

1166 次点击
所在节点    前端开发
0 条回复

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/693203

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX