Refactor and fix nested attribute sorting.