-7

I want to make a list of the richest user using JSON

So there's my code

var users = {'Johnny': {points: 20}, 'Kyle': {points: 30}};

I want it logged in console like

1. Kyle points: 30 2. Johnny points: 20

So how?

Kyle Mods
  • 63
  • 1
  • 9
  • 2
    This is not the kind of question that should be posted on Stack Overflow. We answer questions about specific programming problems that users are experiencing. You don't seem to be asking about a specific problem you are having with code, you are just asking us to write the solution for you. – Scott Marcus Jan 17 '18 at 16:44

1 Answers1

0
Object.keys(users).forEach(function(name, index){
  console.log((index + 1) + '. ' + name + ' points: ' + users[name].points);
});
muZk
  • 2,908
  • 1
  • 21
  • 22
  • I want kyle be number 1 not johnny thanks for your help BTW – Kyle Mods Jan 17 '18 at 16:48
  • If you want to keep order, you have to change your `users` variable from object to an array, something like: `[{ name: 'Kyle', points: 30 }, { name: 'Johnny', points: 20 }]`. – muZk Jan 17 '18 at 16:53
  • Or if you just want to make it work with your example, you can use the following: ```Object.keys(users).reverse().forEach(function(name, index){ console.log((index + 1) + '. ' + name + ' points: ' + users[name].points); });``` (it will sort names in descending ie: order from Z to A) – muZk Jan 17 '18 at 16:54
  • I did it and i got this 1. 0 points: 30 2. 1 points: 20 – Kyle Mods Jan 17 '18 at 16:55
  • If you use array instead of object, the code should be: ```users.forEach(function(user, index){ console.log((index + 1) + '. ' + user.name + ' points: ' + user.points); });``` – muZk Jan 17 '18 at 16:56