简体   繁体   中英

How to get position in json file using JS (node.js)

How do I get position in JSON file like

{
  "some-random-id3": {
    "totalxp": 981
  },
  "some-random-id1": {
    "totalxp": 654
  },
  "some-random-id2": {
    "totalxp": 547
  },
  "some-random-id0": {
    "totalxp": 10
  }
}

I mean, how can i get if i enter "some-random-id2" -> 3. position or "some-random-id3" -> 1. position

I didnt't tried anything bcs I don't know how to do.

There is no defined way of doing this. As the JSON documentation quotes (emphasis added):

An object is an unordered set of name/value pairs.

You might be able to get away with iterating through Object.keys() , but JS objects are also unordered and it is not required to give it to you in the same order every time.

If you're willing to break the JSON specification, then your best bet is to implement your own JSON parser using the Map type, which preserves insertion order. However, this will likely be quite the project. Your other option is to change your data structure. You may want to consider using an array instead (which preserves order), like this:

[{
    id: "some-random-id3",
    value: {
      "totalxp": 981
    }
  },
  {
    id: "some-random-id1",
    value: {
      "totalxp": 654
    }
  },
  {
    id: "some-random-id2",
    value: {
      "totalxp": 547
    }
  },
  {
    id: "some-random-id0",
    value: {
      "totalxp": 10
    }
  }
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM