0

I would like to sort an object based on ascending keys. The solution I implemented only works for one level deep and I would like to get it done for a nested object. Please advice.

var data = {
  player2: {
    score: 6,
    cards: 4
  },
  player1: {
    score: 4,
    cards: 6
  }
};

console.log(Object.fromEntries(
  Object.entries(data).sort()
))

The end result I want is

var data = {
  player1: {
    cards: 6,       
    score: 4,
  },
  player2: {
    cards: 4,
    score: 6
  }
};

I might have a very big nested object. Please advice.

a2441918
  • 1,835
  • 2
  • 12
  • 31
  • 1
    have a look at: https://stackoverflow.com/questions/24629917/sorting-javascript-object-by-key-value-recursively I hope it helps. – Edwin May 09 '19 at 16:57
  • if you have a large object of "players" it would be much better to have an array of objects... let data = [ {id: 'Player1', score: 6, cards 4}, {id: 'player2', score:4, cards: 6}] – GifCo May 09 '19 at 16:59
  • @GifCo Its the redux store in React. I am sorting it for readability in redux dev tools – a2441918 May 09 '19 at 17:09

0 Answers0