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
objects
just as in my OP, but longer and with more key/value pairs and to make that list more "user friendly", need to sort it so its easier to read. And with solution in OP I wonder ifObject.assign()
won't cost much on performance behalf \$\endgroup\$