Home > database >  How to get a single value and value name from an JSON file without knowing the value name
How to get a single value and value name from an JSON file without knowing the value name

Time:07-22

I have a discord bot and it saves achievements in a JSON file. The JSON structure is like this:

{
  "784095768305729566": {
    "coins": 14598,
    "achievements": {
      "taking_inventory": true
    }
  },
}

The command should give you an overview of what achievements you already have.

I want to create an embed and run a for loop for every sub-thing of achievements. If the value is true, the for loop should take the value name and the value and add a field to the embed where the field title is the value name.

I have multiple problems there.

  1. I don't know how to get value names and values. I already tried Object.keys(...) but that gives all keys and not one by one. I don't know how to get the values.
  2. I don't know how to make the for loop as long as all sub-things of achievements.

I tried:

for(var i = 0; i<datafile[id].achievements.length; i  ){...}

but that didn't work wither.

CodePudding user response:

You can get an array of an object's entries (keys and values) from Object.entries. You can filter that array for the value to be true You can map the result to the key. This gives you an array of achievement keys which had the value "true".

const datafile = {
  "784095768305729566": {
    "coins": 14598,
    "achievements": {
      "taking_inventory": true,
      "other_achievement": false
    }
  },
};

const id = "784095768305729566";

const achievements = Object.entries(datafile[id].achievements)
  .filter(([k, v]) => v)
  .map(([k, v]) => k);

// do something with achievements
console.log(achievements);

CodePudding user response:

You can use Object.entries that returns an array of a given object's own enumerable string-keyed property [key, value] pairs:

let user = "784095768305729566"
let obj = {
  "784095768305729566": {
    "coins": 14598,
    "achievements": {
      "taking_inventory": true,
      "another_achievement": true,
      "yet_another_achievement": false,
      "and_one_more": true,
    }
  },
}

let fields = Object.entries(obj[user].achievements)
  .map(([name, value]) => ({
    name,
    value: value ? '✅' : '❌',
    inline: false,
  }))

console.log(fields)

// or if you only want to include achievements a user already has

let onlyTruthyFields = Object.entries(obj[user].achievements)
  // only where value is truthy
  .filter(([name, value]) => value)
  .map(([name, value]) => ({
    name,
    value: '✅',
    inline: false,
  }))

console.log(onlyTruthyFields)

And then just add these to your embed:

embed.addFields(fields)
  • Related