I'm using angular 7 and trying to do something in a child component : use the input property that can be at first level in the object or deeper.
My child component has this piece of code :
if (this.values.filter(obj => obj[this.matchPropertyName] === $event[i].id).length === 0) {
...
}
where this.matchPropertyName is my input (can be 'id', 'myProperty.id',...)
For a single level (obj.id) this code works. However, I need to use sometimes from a deeper level (obj.myProperty.id) and it doesn't work. How can I achieve this ?
Let me know if it not clear enough.
I'm using angular 7 and typescript 3.2.4
I don't think there's a built-in solution but you can make use of a simple split
and reduce
. For example:
const value = this.matchPropertyName.split('.').reduce((pre, curr) => pre[curr], obj);
would give the value for obj.myProperty.id
when this.matchPropertyName="myProperty.id"
So in your case, you could use it like:
const theValue = this.matchPropertyName.split('.').reduce((pre, curr) => pre[curr], obj);
if (this.values.filter(obj => theValue === $event[i].id).length === 0) {
...
}
Final result by the OP:
myEventListener($event) {
if (this.values.filter(obj => this.resolveProperty(obj) === $event[i].id).length === 0) {
...
}
}
resolveProperty(obj) {
return this.matchPropertyName.split('.').reduce((pre, curr) => pre[curr], obj);
}