0

In my angular project, I have the array of objects as below. I need to re-arrange the position of the object using javascript / lodash Does anyone help me?

Response (Array of Object):
[
   { 'name': 'MMK', 'desc': 'test descritpion', 'hrcode': 'EMP001' },
   { 'name': 'SSK', 'desc': 'test descritpion', 'hrcode': 'EMP002' },
   { 'name': 'AAK', 'desc': 'test descritpion', 'hrcode': 'EMP002' },
]

Here, I am getting the response as above and that should be changed the order of the keys, not the value.

Expected value

[
       { 'hrcode': 'EMP001', 'name': 'MMK', 'desc': 'test descritpion' },
       { 'hrcode': 'EMP002', 'name': 'SSK', 'desc': 'test descritpion'  },
       { 'hrcode': 'EMP002', 'name': 'AAK', 'desc': 'test descritpion'  },
    ]
  • Object key order doesn't matter - objects are **unordered** – tymeJV Feb 13 '19 at 17:00
  • [js objects are unordered](https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order). But you can go thru the object and sort they keys based on your preference and then access the values in the order you defined. – Kevin He Feb 13 '19 at 17:00
  • question for OP: why do you want to order object by keys? perhaps we can come up with better solutions if more details are given – ABOS Feb 13 '19 at 17:15
  • I need to generate the TXT file which should have the specific order. I am using anguar2-txt npm to convert the TXT file. – Muthukumar Marichamy Feb 13 '19 at 20:01

1 Answers1

-1

The short answer is you can not. Objects have indeterminate order - even though it usually looks stable when you run a project over and over, you should not rely on their order.

If you really want to iterate through object keys in a particular order for some reason, you can create an array with the keys in the order you want, then iterate over that array. Something like the following:

var response = {... your object ...}
var keyOrder = ['hrcode', 'name', 'desc'];
keyOrder.forEach(key => {
  console.log(key, 'response:', response[key]);
});

Without knowing exactly why you want them in that order, I can't give a better example.

Michael Pratt
  • 3,180
  • 1
  • 14
  • 30