PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, July 23, 2022

[FIXED] How to get a single value and value name from an JSON file without knowing the value name

 July 23, 2022     arrays, discord.js, javascript, json, node.js     No comments   

Issue

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.


Solution

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);



Answered By - James
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing