简体   繁体   English

在javascript中将文字对象转换为特定类的对象

[英]Convert literal object to particular class' object in javascript

I want to convert object literal list from JSON file to particular class object list in javascript, I tried but not able to achieve, can anybody knows how to achieve this in ES5/ES6, since Im trying this in angular 2:我想将对象文字列表从 JSON 文件转换为 javascript 中的特定类对象列表,我尝试过但无法实现,任何人都知道如何在 ES5/ES6 中实现这一点,因为我在 angular 2 中尝试了这个:

Here is my JSON file :这是我的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}
]}

Product Class :产品类别

export class Product{
static newId:number = 0;

constructor(public name: string = "", public cost: number = 0,public id: number = 0){
    this.id = ++Product.newId;
}};

Here "list" array contains list of object literals of type Object , I just want to convert all of them into the object of type "Porduct"这里的“list”数组包含Object类型的对象文字列表,我只想将它们全部转换为“Product”类型的对象

Here is what im tring to do:这是我正在做的事情:

this.appService.getProductList().subscribe(
    data => this.productList = data.list,
    error => console.error("error"),
    () => console.log("GET done.")
  );

Here "appService" is http service, "getProductList()" is service method returns observable, and "this.productList" is an array, I want to fill this array with object of type Product rather simple "Object" .这里“appService”是http服务, “getProductList()”是服务方法返回observable,而“this.productList”是一个数组,我想用Product类型的对象填充这个数组,而不是简单的“Object” Please help me in this.请帮助我。

In your getProductList() in the .map call just transform it to a "real" product:.map调用中的getProductList()中,只需将其转换为“真实”产品:

return this.http.get(...)
           .map(res => res.json().map(p => new Product(p.name, p.cost)));

I wouldn't do it in the subscribe because as a consumer of the getProductList() I'd assume to actually already get Products and not just JS objects.我不会在subscribe这样做,因为作为getProductList()的消费者,我假设实际上已经获得了 Products 而不仅仅是 JS 对象。 The consumer doesn't need to know anything about the implementation detail.消费者不需要知道任何关于实现细节的信息。

I guess this is what you want:我想这就是你想要的:

  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.")
  );

Late answer, but wanted to add one aspect:迟到的答案,但想补充一个方面:

While in most situations creating a new object with the old object as parameter(s) is definitely the best and safest, it's also possible to modify the prototype of an existing object, to effectively make a simple {"name":"ABC", "cost":200} into a Product .虽然在大多数情况下,使用旧对象作为参数创建新对象绝对是最好和最安全的,但也可以修改现有对象的原型,以有效地创建一个简单的{"name":"ABC", "cost":200}变成Product

Example:示例:

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!'

If using TypeScript, you would also either have to cast obj into a Greeter afterwards or just use the fact that Object.setPrototypeOf returns the given object typed using the given Prototype:如果使用 TypeScript,您还必须在之后将obj转换为Greeter ,或者仅使用Object.setPrototypeOf返回使用给定 Prototype 键入的给定对象这一事实:

Object.setPrototypeOf(obj, Greeter.prototype); 
const greeter = obj as Greeter;

or, simpler:或者,更简单:

const greeter = Object.setPrototypeOf(obj, Greeter.prototype); 

Now obj is a Greeter instance (but still of type {name: string} so you cannot do obj.hello() ), but greeter is of type Greeter .现在obj是一个Greeter实例(但仍然是{name: string}类型,所以你不能做obj.hello() ),但greeterGreeter类型。

> obj.hello();
error TS2339: Property 'hello' does not exist on type '{ name: string; }'

> greeter.hello();
Hello World!

Obviously, this might be risky and should only be done with care, since you're asserting that an object not created with Greeter 's constructor is a compatible object having the same properties etc. So in most cases this should probably be avoided, but it's definitely possible.显然,这可能有风险,并且应该小心完成,因为您断言不是使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM