如何将对象符号路径保存到变量中以在模板中使用?

How to save a object notation path in to a variable to use in template?

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

有人帮我吗?

这是我的尝试:

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

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