-2

So essentially I have a JSON that it's in the format as so:

JSON= [
{username: foo, score: 12343}, 
{username: bar, score: 9432}, 
{username: foo-bar, score: 402, ...
]

I know that the JSON that I am getting back is already rank from highest to lowest, based on the scores.

How can I make an array that automatically inserts the rank position? For instance, I would like to see an output of :

[1, username: foo, score: 12343],
[2, username: bar, score: 9432], 
[3, username: foo-bar, score: 402],...
Alejandro
  • 2,266
  • 6
  • 35
  • 63

3 Answers3

0

Javascript got you covered already. An array always has indexes, though it starts at zero. If you want the best, just use

console.log(JSON[0]);

and if you insist on 1 being 1, try this

function getByRank(index) {
   return JSON[index - 1]; 
}

so you will get the best with

console.log(getByRank(1)); // {username: "foo", score: 12343}

I think in your code the json is valid json, see the " around foo...

baao
  • 71,625
  • 17
  • 143
  • 203
0

Your syntax seems off, but assuming that the JSON is:

JSON = [
  {username: 'foo', score: 12343}, 
  {username: 'bar', score: 9432}, 
  {username: 'foo-bar', score: 402}
]

Since Arrays are 0 indexed and you have access to the current index in a .map method, you can do something along the following:

JSON = JSON.map(function (record, index) {
  record.rank = index + 1;
  return record;
})

This should give you the following output:

[ 
  { rank: 1, username: 'foo', score: 12343 },
  { rank: 2, username: 'bar', score: 9432},
  { rank: 3, username: 'foo-bar', score: 402}
]

Hope this helps.

Ian
  • 480
  • 5
  • 8
0

Strictly from the point of view of your question, you already got the answer. I just want to enumerate some ideas, maybe they will be useful to some of you in the future:

  1. First of all, JSON (JavaScript Object Notation) is an open-standard format that uses human-readable text to serialize objects, arrays, numbers, strings, booleans, and null. Its syntax, as the name states, is derived from JavaScript, but JSON is actually a text, a string.

  2. A JSON string is (almost always) syntactically correct JavaScript code.

  3. Make sure you don't use the keyword "JSON" as the name of a variable, because JSON is actually an existing object in JavaScript, and it is used to encode to JSON format (stringify) and decode from JSON format (parse). Just try JSON.stringify({a: 2, b: 3}); and JSON.parse('{"a":2,"b":3}'); in a JavaScript console.

Community
  • 1
  • 1
Zoli Szabó
  • 4,366
  • 1
  • 13
  • 19