我想将对象文字列表从JSON文件转换为javascript中的特定类对象列表,我尝试但无法实现,任何人都知道如何在ES5 / ES6中实现这一点,因为我在角度2中尝试这个:< / p>
这是我的 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”数组包含对象类型的对象文字列表,我只想将它们全部转换为“Porduct”类型的对象
这是我要做的事情:
this.appService.getProductList().subscribe(
data => this.productList = data.list,
error => console.error("error"),
() => console.log("GET done.")
);
此处“appService”是http服务,“getProductList()”是服务方法返回observable,“this.productList”是一个数组,我想用产品类型的对象填充这个数组,相当简单“对象”。请帮助我。
答案 0 :(得分:3)
在getProductList()
电话中的.map
中,只需将其转换为“真实”产品:
return this.http.get(...)
.map(res => res.json().map(p => new Product(p.name, p.cost)));
我不会在subscribe
中这样做,因为作为getProductList()
的消费者,我假设实际上已经获得了产品,而不仅仅是JS对象。消费者不需要了解有关实现细节的任何信息。
答案 1 :(得分:2)
我想这就是你想要的:
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.")
);
答案 2 :(得分:0)
this.appService.getProductList().subscribe(
data => this.productList = data.list.map( (listItem) => new Product(listItem),
error => console.error("error"),
() => console.log("GET done.")
);
答案 3 :(得分:0)
最新答案,但想补充一个方面:
虽然在大多数情况下以旧对象作为参数创建新对象绝对是最好和最安全的方法,但也可以修改现有对象的原型,以有效地将简单的{"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
返回使用给定原型键入的给定对象的事实:>
Object.setPrototypeOf(obj, Greeter.prototype);
const greeter = obj as Greeter;
或更简单:
const greeter = Object.setPrototypeOf(obj, Greeter.prototype);
现在obj
是一个Greeter
实例(但仍然是{name: string}
类型,因此您无法执行obj.hello()
),但是greeter
是{{1 }}。
Greeter
显然,这可能有风险,应该谨慎行事,因为您断言不是使用> obj.hello();
error TS2339: Property 'hello' does not exist on type '{ name: string; }'
> greeter.hello();
Hello World!
的构造函数创建的对象是具有相同属性等的兼容对象。因此,在大多数情况下,应该避免这种情况,但是绝对有可能。