Skip to main content
3 of 3
edited tags
200_success
  • 144.2k
  • 22
  • 188
  • 473

Angular, sort objects by their keys

I had to sort a list of objects - {name:'name', email:'email} by their keys, ex. by email, so they all be rendered with email key/value pair as a first key/value pair and I was surprised about the solution i came up to - Object.assign() when i loop through array and assign email key/value pair to each object:

objects = [{name: 'name1', phone: 'phone1', email: 'email1'},
            {name: 'name1', phone: 'phone1', email: 'email1'},
            {name: 'name1', phone: 'phone1', email: 'email1'}]

sort(val) {    
  for (let i=0; i < this.objects.length; i++) {
    let temp = {};
    temp[val] = null; 
    this.objects[i] = Object.assign(temp, this.objects[i])  
  }
}

The rest is done by Angular's ChangeDetection. Are there better ways or can you tell any possible issues with this? (I still don't feel very proficient in Javascript, so just wondering)

Here is a StackBlitz's DEMO