[英]Convert literal object to particular class' object in javascript
我想将对象文字列表从 JSON 文件转换为 javascript 中的特定类对象列表,我尝试过但无法实现,任何人都知道如何在 ES5/ES6 中实现这一点,因为我在 angular 2 中尝试了这个:
这是我的JSON 文件:
{"list":[
{"name":"ABC", "cost":200},
{"name":"LMN", "cost":100},
{"name":"POP", "cost":200},
{"name":"OEE", "cost":560},
{"name":"WWO", "cost":450},
{"name":"ERR", "cost":150},
{"name":"OWE", "cost":250}
]}
产品类别:
export class Product{
static newId:number = 0;
constructor(public name: string = "", public cost: number = 0,public id: number = 0){
this.id = ++Product.newId;
}};
这里的“list”数组包含Object类型的对象文字列表,我只想将它们全部转换为“Product”类型的对象
这是我正在做的事情:
this.appService.getProductList().subscribe(
data => this.productList = data.list,
error => console.error("error"),
() => console.log("GET done.")
);
这里“appService”是http服务, “getProductList()”是服务方法返回observable,而“this.productList”是一个数组,我想用Product类型的对象填充这个数组,而不是简单的“Object” 。 请帮助我。
在.map
调用中的getProductList()
中,只需将其转换为“真实”产品:
return this.http.get(...)
.map(res => res.json().map(p => new Product(p.name, p.cost)));
我不会在subscribe
这样做,因为作为getProductList()
的消费者,我假设实际上已经获得了 Products 而不仅仅是 JS 对象。 消费者不需要知道任何关于实现细节的信息。
我想这就是你想要的:
this.appService.getProductList().subscribe(
data => this.productList = data.list.map(item => new Product(item.name, item.cost));
error => console.error("error"),
() => console.log("GET done.")
);
迟到的答案,但想补充一个方面:
虽然在大多数情况下,使用旧对象作为参数创建新对象绝对是最好和最安全的,但也可以修改现有对象的原型,以有效地创建一个简单的{"name":"ABC", "cost":200}
变成Product
。
示例:
class Greeter {
constructor(public name: string) {
}
hello() {
console.log(`Hello ${this.name}!`);
}
}
const obj = {name: 'World'}; // Normal object literal which is not a Greeter instance
obj.hello(); // Error
Object.setPrototypeOf(obj, Greeter.prototype); // Now obj is a Greeter instance
obj.hello(); // Prints 'Hello world!'
如果使用 TypeScript,您还必须在之后将obj
转换为Greeter
,或者仅使用Object.setPrototypeOf
返回使用给定 Prototype 键入的给定对象这一事实:
Object.setPrototypeOf(obj, Greeter.prototype);
const greeter = obj as Greeter;
或者,更简单:
const greeter = Object.setPrototypeOf(obj, Greeter.prototype);
现在obj
是一个Greeter
实例(但仍然是{name: string}
类型,所以你不能做obj.hello()
),但greeter
是Greeter
类型。
> obj.hello();
error TS2339: Property 'hello' does not exist on type '{ name: string; }'
> greeter.hello();
Hello World!
显然,这可能有风险,并且应该小心完成,因为您断言不是使用Greeter
的构造函数创建的对象是具有相同属性等的兼容对象。因此在大多数情况下应该避免这种情况,但是这绝对有可能。
this.appService.getProductList().subscribe(
data => this.productList = data.list.map( (listItem) => new Product(listItem),
error => console.error("error"),
() => console.log("GET done.")
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.