Sorting a Map with JSON data as values

{"5eaa9ce8": {
            "Id": "1958208",
            "priority": 0
             },
"5eaa9bs8": {
            "Id": "1958208",
            "priority": 2
             },
"6eaa9ce8": {
            "Id": "1958208",
            "priority": 1
             }
}

Need to sort this Map based on the priority of the key.

1 answer

  • answered 2018-11-08 07:24 Suhas NM

    Json objects won't maintain order, to preserve order use Arrays

    step 1: convert your Object to array:

    keys = Object.keys(yourObj)
    for(let i=0;i<keys.length;i++){
       yourArr.push(keys[i])
    }
    

    step 2: sort your array:

    function compare(a,b) {
      aKey = Object.keys(a)[0];
      bKey = Object.keys(b)[0];
      if (a[akey].priority < b[bKey].priority)
        return -1;
      if (a[aKey].priority > b[bKey].priority )
        return 1;
      return 0;
    }
    yourArr.sort(compare)
    

    hope this helps!!