0

Goodmorning, I am having a problem figuring out how to sort the following JSON

{
    "135": {"name": "marco", "title": "foo"},
    "223": {"name": "wilco", "title": "bar"},
    "322": {"name": "enola", "title": "baz"}
}

I wish to sort by name (and sometimes, possible title. However the complete line should be sorted. Should I convert this into an proper array first?

Thanks!

Marco
  • 2,463
  • 3
  • 23
  • 20

4 Answers4

3

Should I convert this into an proper array first?

Yes, since objects don't guarantee order. Additionally, you'd have to modify the structure a bit:

[
    {"id":"135", "name": "marco", "title": "foo"},
    {"id":"223", "name": "wilco", "title": "bar"},
    {"id":"322", "name": "enola", "title": "baz"}
]

As for sorting algorithms, there are a lot on the web, especially this one.

Community
  • 1
  • 1
Joseph
  • 117,725
  • 30
  • 181
  • 234
1

you may want to lookat underscore which makes working with objects/arrays easier for you. Yeap, you need to make it into an array, so that you can even have a reliable order/sort it.

var array=[];
for (var i in obj){
    if (obj.hasOwnProperty(i)){
        obj[i].id=i;
        array.push(obj[i]);
    }
}
var fieldToSort="id"; //or "title" or "name"
array.sort(function(a,b){
    return a[fieldToSort] - b[fieldToSort];
});
japrescott
  • 4,736
  • 3
  • 25
  • 37
1

You can never sort an object. You need to convert this into an array.

For this particular problem if you cannot change the object into array.

You can follow this,

var obj = { 
    "223": {"name": "wilco", "title": "bar"},
    "322": {"name": "enola", "title": "baz"},
    "135": {"name": "marco", "title": "foo"}
};

var arr = [];
for(var i in obj) {
    var o = {};
    if(obj.hasOwnProperty(i)) {
       o.id = i;
       o.name = obj[i].name;
       o.title = obj[i].title;
       arr.push(o); 
    }        
} 
arr.sort(function (a,b) {
   a.id - b.id;
});
console.log(arr);

Demo

Jashwant
  • 28,410
  • 16
  • 70
  • 105
1

You can try to sort your object props without creating an array, but it will cost you more lines of code to write, and you have to watch for your properties, so they didn't inherited from other objects. So you have to use for in loop:

for (var prop in obj) {
  if(obj.hasOwnProperty(prop)) {
    //perform sorting...
  }
}

Or you can transform your object into an array and sort data via standard js array sorting function:

function sortObj(obj) {
  var objToArr = [],
  prop,
  sortedObj = {};
  for (prop in obj) {
    if (obj.hasOwnProperty(prop)) {
        objToArr.push([prop, obj[prop]]);
    }
   }

 objToArr.sort(function(a, b) { return a[0] - b[0]; });
 objToArr.forEach(function (val, key) {
   sortedObj[val[0]] = sortedObj[val[1]];
 });
 return sortedObj;
}

You can adopt this function for more complex objects, for example when one property of object contains another object, etc.

happyCoda
  • 418
  • 2
  • 2