typescript - 如何将对象符号路径保存到要在模板中使用的变量中?
问题描述
我需要从很长的路径中获取数据。所以我尝试将路径存储在变量中并决定添加到模板中。但不起作用。
有人帮我吗?
这是我的尝试:
我的存储路径:propBasePath:string =
${header.label.lacales}
当我这样安慰时:
this.appProps = value;
console.log( this.appProps[this.propBasePath]['th_TH'] ) //this is not works!!
console.log( this.appProps.header.label.lacales.th_TH ) it's works.
在模板中:
<h1 style="font-size: 3rem">{{appProps[propBasePath].th_TH}}</h1>
以上也不起作用。我知道我试图检索数据的方式是错误的。但是请任何人纠正我吗?
我也收到此错误ERROR ReferenceError: header is not defined
解决方案
事实上,你不能这样做。您无法通过传递路径从对象中找到属性,myObject['prop1.prop2.prop3']
因为它会尝试查找属性prop1.prop2.prop3
本身。
为了解决您的问题,您可以执行类似以下示例的操作来获取每个属性,然后再深入研究结果并获取下一个属性,直到您获得所需的属性。
const obj = {
prop1: {
prop2: {
prop3: 'The value you are looking for'
}
}
};
const myPath = 'prop1.prop2.prop3';
const deepValue = myPath.split('.').reduce((obj, current) => obj[current], obj);
console.log(deepValue);
我希望这个例子对你有帮助:)
推荐阅读
- php - EasyApache 4 在加载配置文件时冻结
- javascript - 单击并返回时将超链接文本更改为下拉列表
- python-3.x - 试图让我的随机骰子生成器继续提供随机数
- database - postgresql 中的 Odoo 表比其他 MySQL/Oracle/MSSQL 数据库表大吗?
- perl - 如何在 Perl 中将图像或文本文件转换为字节数组?
- android-instant-apps - 上传 Instant App 问题:Instant App APK 中的配置 APK 应该有定位信息
- architecture - 报告整合组成
- java - Spring Boot Rest根据参数调用
- python - SQLAlchemy 与额外列的多对多关系
- python - Python套接字未从服务器接收数据字节