-1

So, there will probably be guys that will say this is a duplicate, but I read many relatively similar questions and still I'm unable to find an answer that resolves this particular problem, I've even tried some npm modules that claim to solve this, but to no avail...

Well, I have an array of objects:

 var objArr = [{ '5': 1,'6': 1,'34': 3,id: 1,question: '12',author: 'Zoran  Stanić' }];

and another array which should help in sorting the first array:

var sortingArr = [ 'id', 'question', 'author', '34', '5', '6' ];

The result should be this:

[{id: 1, question: '12', author: 'Zoran  Stanić', '34': 3, '5': 1, '6': 1}]

How can I achieve this?

P.S. These are the values from the database, and the order of objArr could be completely different than the one in example, depending on the db logic - it's MySQL thingy.

pilgrim011
  • 57
  • 1
  • 7

3 Answers3

0

Note: you cannot sort an object's keys, that depends on browser implementation....nor does it matter what "order" an objects keys are in, it only matters to you or your users what you display/how you display it.

If you want to print things out in a certain way, then you can do the following:

var arrOfObjects = [{...}];
var sortingArr = [ 'id', 'question', 'author', '34', '5', '6' ];

arrOfObjects.forEach(function(obj) {
   sortingArr.forEach(function(k) {
      console.log(k + ':' + obj[k]);
   });
});
Adam Jenkins
  • 51,445
  • 11
  • 72
  • 100
  • Didn't know that. I'm using this code server-side (Node.js), and after I solve this (and do some other things in Node), I'll render the view for the user. Thanks for the answer, I'll look at it when I wake up, it's late here... – pilgrim011 Jun 09 '17 at 00:05
  • AFAIK with ES6, the (traversal) order of object properties has been specified to match the most common implementations - see http://2ality.com/2015/10/property-traversal-order-es6.html – le_m Jun 09 '17 at 00:24
0

Objects cannot be sorted in JS. You'd either have to do create your own implementation using an Array. If you can use ES6, Map will maintain the order with which pairs are added. The link below talks about this:

http://www.jstips.co/en/javascript/map-to-the-rescue-adding-order-to-object-properties/

Thomas Maddocks
  • 1,355
  • 9
  • 24
0

Alternatively, you can have an array or arrays, in which every array conforms to the structure of sortingArr, like this:

var objArr = [{ '5': 1,'6': 1,'34': 3,id: 1,question: '12',author: 'Zoran  Stanić' }];

var sortingArr = [ 'id', 'question', 'author', '34', '5', '6' ];

var sortedArrsVals = objArr.map(el => 
  sortingArr.map(e => el[e])
)

console.log(sortedArrsVals)
Mμ.
  • 8,382
  • 3
  • 26
  • 36