[英]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.