I have an API that looks like this:
{
"id": 749,
"firstName": "Ishna",
"lastName": "Willis",
"email": "Mawfly@awgawggwagov",
"phone": "(162)932-3460",
"adress": {
"streetAddress": "7006 Sed Ave",
"city": "Colfax",
"state": "WI",
"zip": "71085"
},
"description": "{lorem|32"
},
and I sort this API ascending and descending.
function sortInfo(e) {
const column = e.target.dataset.column;
const order = e.target.dataset.order;
let changeData = e.target;
if(order === 'desc') {
changeData.setAttribute('data-order', 'asc');
searchResult.fetchResult().then(response => {
response.sort((a,b) => a[column] > b[column] ? 1 : -1);
buildTable(response)
})
} else {
changeData.setAttribute('data-order', 'desc');
searchResult.fetchResult().then(response => {
response.sort((a,b) => a[column] < b[column] ? 1 : -1);
buildTable(response)
})
}
}
It works fine if I sort by name or surname, however, I also need to sort specifically by state. I have a data attribute but even if I make it adress.state when it is given to the column it wont work. Is there a way to refactor this code to access address.state?
I would suggest to create separate function to sort by address, then it will be easier to work on he data without adding tons of ifs inside of current function.
Another way that I can think about is to flat your object for sorting purpose then you will be able to sort by all of object properties and thed bring back original structure.