I have a use case where I need to use a string to match object values
For example
'one': {
'two': {
'three': 'val'
}
}
}
split
and reduce
seems to be the way to go about this, but I have not gotten it to work using the code below
const string = 'one.two.three';
const test = string
.split('.')
.reduce((obj, key) => {
return obj[key]
});
console.log(test);
//expected one['two']['three']
[ Edit to add more context ] I have an HTML Template (angular 7) that calls the sort function
(click)="sortColumn('spn.subscriptionId')"
I have the following object to keep track of sort order for each column
public sortableColumns = [
{ colName: 'name', colSortDir: 'none'},
{ colName: 'spn.subId', colSortDir: 'none'},
{ colName: 'regionName', colSortDir: 'none'},
{ colName: 'customerName', colSortDir: 'none'}
];
and the sortColumn
function. this.subscriptions
comes from a rest api. the sort function works if there is a rest api object only has one level - 'name' but does not work for the nested object - spn.subscriptionId
public sortColumn(column : string) {
// resets other columns
this.sortableColumns.forEach((el) => {
if (el.colName !== column) {
el.colSortDir = 'none';
}
});
// matches the column name passed with sortableColumns to set order in UI
const col = this.sortableColumns.filter((el) => {
return el.colName === column;
});
// sorting of the array object. this.subscriptions comes fr
if (col[0].colSortDir === 'asc') {
col[0].colSortDir = 'dsc';
this.subscriptions.sort((val1, val2) => {
if (val1[column] < val2[column]) {
return -1;
} else if (val1[column] > val2[column]) {
return 1;
} else {
return 0;
}
});
} else if (col[0].colSortDir === 'none' || col[0].colSortDir === 'dsc') {
col[0].colSortDir = 'asc';
this.subscriptions.sort((val1, val2) => {
if (val1[column] > val2[column]) {
return -1;
} else if (val1[column] < val2[column]) {
return 1;
} else {
return 0;
}
});
}
}