从JSON文件读取,变量名称不同,与

时间:2018-04-30 02:35:10

标签: javascript json angular typescript

我正在尝试从JSON文件中读取,但它的格式是这样的:

[
    {
        "INV#" : "123"
    },
    {
        "INV#" : "456"
    }
]

该变量名称不符合JavaScript或TypeScript命名。所以我有以下对象:

export interface Invoice {
    invoiceNumber: number;
}

class myclass {
    private inv: Invoice[];
}

如何从该json文件读取到此对象中。无法对数据库变量进行更改。在JavaScript中无法更改我的接口变量的名称。不知怎的,他们必须匹配,但必须有办法让对象属性成为我的。

1 个答案:

答案 0 :(得分:0)

// let's assume that you've read the json into some variable
let response = [
    {
        "INV#" : "123"
    },
    {
        "INV#" : "456"
    }
];

export interface Invoice {
    invoiceNumber: number;
}

class myclass {
    private inv: Invoice[];
    constructor(_response: any[]) {
        // do not forget to check _response for null/undefined, if it is an array or not, etc.
        this.inv = _response.map(obj => <Invoice>{
            invoiceNumber: parseInt(obj['INV#'])
        });
    }
}

// usage:
let some_var = new myclass(response);

// now some_var contains array of invoices internally.