Search code examples
node.jsjsonsortingleaderboard

Json Filter Objects Into Different Array


Let's Say I Have This user data under

{
  "asdfasdf": {
    "user": "asdfasdf",
    "skillpoints": 0,
    "acc": 0,
    "sessions": 0,
    "wpm": 0
  },
  "matthewproskils": {
    "user": "matthewproskils",
    "skillpoints": 0,
    "acc": 0,
    "sessions": 0
  }
}

Is there any way to sort this data into an 3 arrays? I want the arrays to have a result of [[matthewproskils, 0],[asdfasdf, 0]]


Solution

  • Well you example seems to only have 2 Keys within the original JSON.

    But if you want to Create an array of keys and array of contents you can

    const jsonObject = {
      "asdfasdf": {
        "user": "asdfasdf",
        "skillpoints": 0,
        "acc": 0,
        "sessions": 0,
        "wpm": 0
      },
      "matthewproskils": {
        "user": "matthewproskils",
        "skillpoints": 0,
        "acc": 0,
        "sessions": 0
      }
    }
    
    let keys= [];
    let keyContents = [];
    
    for (const [key, value] of Object.entries(jsonObject)) {
      keys.push(key);
      keyContents.push(value);
    }
    

    it will output

    keys = ['asdfasdf','matthewproskils']
    keyContents [{
            "user": "matthewproskils",
            "skillpoints": 0,
            "acc": 0,
            "sessions": 0
          },{
        "user": "matthewproskils",
        "skillpoints": 0,
        "acc": 0,
        "sessions": 0
      }];