首页 > 解决方案 > 如何将对象符号路径保存到要在模板中使用的变量中?

问题描述

我需要从很长的路径中获取数据。所以我尝试将路径存储在变量中并决定添加到模板中。但不起作用。

有人帮我吗?

这是我的尝试:

我的存储路径: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

标签: typescriptangular5mustache

解决方案


事实上,你不能这样做。您无法通过传递路径从对象中找到属性,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);

我希望这个例子对你有帮助:)


推荐阅读