-2
{"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.

and needed output is { "5eaa9bs8": { "Id": "1958208", "priority": 2 }, "6eaa9ce8": { "Id": "1958208", "priority": 1 }, "5eaa9ce8": { "Id": "1958208", "priority": 0 } }

Raam Krish
  • 31
  • 1
  • 5

1 Answers1

0

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!!

Suhas NM
  • 960
  • 7
  • 10