相关疑难解决方法(0)

在JavaScript中将JSON字符串解析为特定对象原型

我知道如何解析JSON字符串并将其转换为JavaScript对象.您可以JSON.parse()在现代浏览器(和IE9 +)中使用.

这很好,但是如何将JavaScript对象转换为特定的 JavaScript对象(即使用某个原型)?

例如,假设你有:

function Foo()
{
   this.a = 3;
   this.b = 2;
   this.test = function() {return this.a*this.b;};
}
var fooObj = new Foo();
alert(fooObj.test() ); //Prints 6
var fooJSON = JSON.parse({"a":4, "b": 3});
//Something to convert fooJSON into a Foo Object
//....... (this is what I am missing)
alert(fooJSON.test() ); //Prints 12
Run Code Online (Sandbox Code Playgroud)

同样,我不知道如何将JSON字符串转换为通用JavaScript对象.我想知道如何将JSON字符串转换为"Foo"对象.也就是说,我的对象现在应该有一个函数'test'和属性'a'和'b'.

更新 在做了一些研究后,我想到了......

Object.cast = function cast(rawObj, constructor)
{
    var obj = new constructor();
    for(var i in rawObj)
        obj[i] = rawObj[i];
    return obj; …
Run Code Online (Sandbox Code Playgroud)

javascript parsing json prototype object

163
推荐指数
6
解决办法
15万
查看次数

如何在不丢失TypeScript类属性的情况下将JSON对象列表转换为TypeScript对象列表?

我有这个Customer类:

export class Customer {
    id: number;
    company: string;
    firstName: string;
    lastName: string;

    name(): string {
        if (this.company)
            return this.company;
        if (this.lastName && this.firstName)
            return this.lastName + ", " + this.firstName;
        if (this.lastName)
            return this.lastName;
        if (this.firstName)
            return this.firstName;
        if (this.id > 0)
            return "#" + this.id;
        return "New Customer";
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的控制器中,我下载了一个客户列表:

export class CustomersController {
    static $inject = ["customerService", "workflowService"];

    ready: boolean;
    customers: Array<Customer>;

    constructor(customerService: CustomerService, workflowService: WorkflowService) {
        customerService.getAll().then(
            (response) => {
                this.customers = response.data;
                this.ready = …
Run Code Online (Sandbox Code Playgroud)

javascript typescript

4
推荐指数
1
解决办法
3809
查看次数

标签 统计

javascript ×2

json ×1

object ×1

parsing ×1

prototype ×1

typescript ×1