[英]JavaScript insert string into an object iteration
I am working on a function for an Angular Pipe and one of the arguments needs to be a string from the template *ngFor="let row of tableRows | filter: searchText : keyName"
and then use that to itterate the object in the pipe's function 我正在为Angular Pipe创建函数,并且其中一个参数需要为模板中的字符串
*ngFor="let row of tableRows | filter: searchText : keyName"
,然后使用该参数在管道函数中初始化对象
in component: let keyName = 'name.value'
在组件中:
let keyName = 'name.value'
pipe: 管:
transform(items: any[], searchText: string, keyName: string = ''): any[] {
if (!items) {
return [];
}
if (!searchText) {
return items;
}
searchText = searchText.toLowerCase();
console.log(keyName);
return items.filter( it => {
return it.keyName.toLowerCase().includes(searchText); //THIS HERE NEEDS TO MATCH THE STRING PROVIDED
});
}
so lets say the argument string name.value
is passed into the function, it.keyName.toLowerCase()
needs to get interpreted as it.name.value.toLowerCase()
所以可以说参数字符串
name.value
被传递到函数中, it.keyName.toLowerCase()
需要被解释为it.name.value.toLowerCase()
You can use the property accessor bracket notation (eg object[property]
) to access the nested property. 您可以使用属性访问方括号表示法 (例如
object[property]
)来访问嵌套的属性。
For instance try the deepAccessUsingString
function described here: https://medium.com/@chekofif/using-es6-s-proxy-for-safe-object-property-access-f42fa4380b2c 例如,请尝试此处描述的
deepAccessUsingString
函数: https : deepAccessUsingString
function deepAccessUsingString(obj, key){
return key.split('.').reduce((nestedObject, key) => {
if(nestedObject && key in nestedObject) {
return nestedObject[key];
}
return undefined;
}, obj);
}
Use as follows in your code: 在代码中使用以下代码:
return deepAccessUsingString(it, keyName).toLowerCase().includes(searchText);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.