我有下面的界面。
interface ProductJson {
id: number;
name: string;
price: number;
}我希望价格有多个别名,如价格和别名: rate等。如何读取json数据属性“rate”和“price”。
发布于 2019-12-27 03:54:55
一种方法是维护一组要作为别名的attribute名称。
然后将接口属性price添加到json本身(如果它包含别名属性,如rate或amount )。
现在,您可以简单地从else where访问price,这应该会提供相同的值
例如:
var price_group = ['price', 'rate', 'amount'];
var some_other_group = []
var resp = {rate: 200, p: 12}
var resp2 = {price: 300, p: 12};
Object.keys(resp).forEach(key => {
if(price_group.indexOf(key) > -1){
resp.price = resp[key]
}
});
console.log(resp.price)
Object.keys(resp2).forEach(key => {
if(price_group.indexOf(key) > -1){
resp.price = resp[key]
}
});
console.log(resp2.price)
发布于 2019-12-27 03:56:54
您可以使用自定义序列化程序在字段之间创建别名:
使用@kaiu/serializer的示例
class ProductJson {
id: number;
name: string;
@FieldName('rate')
price: number;
}或者,您也可以创建一个getter方法,并使用serializert将您的JSON映射到一个类实例,以便直接使用您的方法,有关更深入的内容,请参阅https://kaiu-lab.github.io/serializer/。
发布于 2019-12-27 03:46:47
我不确定你能不能做到。
通过编写读/写json的程序,你可以很容易地做到这一点,只需将其写为{ price : number }即可接受rate、price、moolah等内容
编辑:我的意思是,你将用户输入或任何其他指定了{moolah: 30}的输入放在你的json中的{price: 30}上。
https://stackoverflow.com/questions/59492736
复制相似问题