-1

I am facing a rather unusual problem using _.object(underscore library call). Below is my code :

var sortable =  [ [ 'c', 107 ],[ 'd', 59 ],[ 'e', 53 ],[ '5', 53 ],[ '6', 26 ],[ '3', 19 ],[ 'a', 10 ],[ '8', 7 ],[ '2', 5 ], [ '7', 4 ],[ '1', 3 ], [ '9', 3 ]];
         sortDict = _.object(sortable);

My output should be :

sortDict = { 'c':107 ,'d': 59,'e': 53 ,'5': 53,'6': 26,'3': 19,'a':10,'8': 7 ,'2':5, '7': 4,'1': 3, '9': 3 }

But what I am getting has me confused, see the output below :

sortDict = {'1': 3, '2':5, '3': 19, '5': 53, '6': 26, '7': 4, '8': 7 , '9': 3 , 'c':107 , 'd': 59, 'e': 53 , 'a':10 }

I am just trying to convert an array to an object here, but the order seems to have changed. Can you please help me achieve my desired output by any means.

user3365783
  • 107
  • 1
  • 9

2 Answers2

1
var sortable = [
    ['c', 107],
    ['d', 59],
    ['e', 53],
    ['5', 53],
    ['6', 26],
    ['3', 19],
    ['a', 10],
    ['8', 7],
    ['2', 5],
    ['7', 4],
    ['1', 3],
    ['9', 3]
];
var sorted = '';
sorted +='{';
for (var i = 0; i < sortable.length; i++) {
    sorted += "'"+sortable[i][0]+"': " +sortable[i][1]+",";
}
sorted +='}';
var obj = sorted;
alert(JSON.stringify(obj));
alert(sorted);
Soni Kamal
  • 20
  • 2
0

If you are required to send an actual JSON object in sorted order, you can do that, because you can always write the string version of it in a specific order (you have a sorted array, right?). (JSON fundamentally being a string representation of a Javascript object.) But the in-memory representation of that Javascript object has no order constraints and its elements will come back via for...in in the order determined by whatever Javascript engine processes it. Even Object.keys() doesn't guarantee an order, but it does give you something you can sort.

If the receiving end of your data also uses Javascript, specifying an ordered object is pointless because it won't iterate that way; if the receiving end is Java, C#, or C++, then its inability to handle the data in any supplied order is pretty much a weakness in the design of that code. There is no a priori reason an unordered object should be delivered in a specific order because that's the opposite of 'unordered' and indicates that the requirements were written by someone...well, not completely qualified. (In fact, the idea that the keys must be delivered in a certain order implies a certain dangerous dependency between leading and trailing keys, and that should make you uncomfortable with the design.)

user1329482
  • 569
  • 3
  • 8