1

Following is my JavaScript object.

{
  "014b9d42":{
    "notification": 0,
    "userName": "adam"
  },
  "02f5b60e": {
    "notification": 3,
    "userName": "jake"
  },
  "1281d8fb": {
    "notification": 1,
    "userName": "eomer"
  },
  "12a2a564": {
    "notification": 0,
    "userName": "bella"
  }
}

I want to sort the above object based on value of notification. How can i do it using underscore js?

sparrow
  • 1,825
  • 6
  • 24
  • 35

2 Answers2

3

As @adeneo pointed out, order in objects is not guaranteed. You'll need to convert the object to an array, then sort based on the notification property.

var jsonObj = JSON;

var arr = [];
for (var key in jsonObj) {
  if (jsonObj.hasOwnProperty(key)) {
    var o = jsonObj[key];
    arr.push({ id: key, notification: o.notification, userName: o.userName });
  }
}

arr.sort(function(obj1, obj2) {
  return obj1.notification - obj2.notification;
});

Here's a working JSFiddle.

Community
  • 1
  • 1
Brett DeWoody
  • 59,771
  • 29
  • 135
  • 184
1

The JSON you gave is not a list. Hence it cannot be sorted. If this was a list then you can use the following code:

var a = [
    {"014b9d42": {
        "notification": 0,
        "userName": "adam"
    }},
    {"02f5b60e": {
        "notification": 3,
        "userName": "jake"
    }},
    {"1281d8fb": {
        "notification": 1,
        "userName": "eomer"
    }},
    {"12a2a564": {
        "notification": 0,
        "userName": "bella"
    }}
];

var sorted = _.sortBy(a, function(item) { 
   var key = [Object.keys(item)[0]];
   return item[key]['notification']; 
});

console.log(sorted);
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>