Sort the values of a JSON file

0

I have a JSON file, and what I want to do is make a function in which I return an ordered list limited by 10 users (if possible, in an array, but if that is complicated, I would appreciate your suggestion).

This data comes from:

let points = JSON.parse(fs.readFileSync('./points.json', 'utf8'));

In which I access the data of each one with the following line:

let userData = points[msg.author.id];

The JSON file has the following format.

{
  "242043489611808769":{"points":617,"level":4,"time":1482316617392},
  "129213229221019648":{"points":22,"level":0,"time":1482316617609},
  "190388892799598592":{"points":214,"level":2,"time":1482316612355}
}

At the moment, what I have is a program that does is add points to users (and as they reach 'x' points, automatically level up), but now I need to make a list of the top 10 most users assets ".

What I need is that when ordering, return the ID (in the first case it would be 242043489611808769 ), which is what I need to be able to process the data.

Work with NodeJS, thanks in advance.

    
asked by Antonio Roman 21.12.2016 в 11:52
source

1 answer

1

You can use the following code to sort the data and get the highest:

/* Los datos que has proporcionado en el ejemplo */
var json = '{\
  "242043489611808769": {\
    "points": 617,\
    "level":4,\
    "time":1482316617392\
  },\
  "129213229221019648": {\
    "points": 22,\
    "level":0,\
    "time":1482316617609\
  },\
  "190388892799598592": {\
    "points":214,\
    "level":2,\
    "time":1482316612355\
  }\
}';
/* Tratamos los datos */
var points = JSON.parse(json);
/* Los convertimos en un array añadiendo el "id" a los campos */
var points_array = Object.keys(points).map(
  function (clave) {
    var elemento = points[clave];
    elemento.id = clave;
    return elemento;
  }
);
/* Los ordenamos comparando los puntos (points) */
points_array.sort(
  function(a, b) {
    return b.points - a.points;
  }
);
/* Obtenemos el primer elemento (el mayor) */
console.log(points_array[0]);
console.log(points_array[0].id);

I hope you find it useful.

    
answered by 21.12.2016 / 12:20
source