Is there a way to specifically extract the Discord data from a JSON file?

I am dealing with an array of objects, each containing an identifiers array that includes strings. Among these strings is a Discord ID, but its position keeps changing unpredictably. This makes it impossible for me to reference the 4th identifier consistently.

All I require is the discord property.

https://i.sstatic.net/dQYFw.png

I have attempted various approaches, but I believe what I need is just the "discord" property. However, I am unsure how to tackle this and implement it in my code. Click on the image to learn more. You will find a json file there related to ${players[i].identifiers[4]


const updateMessage = function() {
    getVars().then((vars) => {
      getPlayers().then((players) => {
        if (players.length !== LAST_COUNT) log(LOG_LEVELS.INFO,`${players.length} players`);
        let queue = vars['Queue'];
        let embed = UpdateEmbed()
        .addField('Server Status','<:yes:847199217063297056> Online',true)
        .addField('In Queue',queue === 'Enabled' || queue === undefined ? '0' : queue.split(':')[1].trim(),true)
        .addField('Players Online',`${players.length}/${MAX_PLAYERS}\n\u200b\n`,true);
        // .addField('\u200b','\u200b\n\u200b\n',true);
        if (players.length > 0) {
          // method D
          const fieldCount = 3;
          const fields = new Array(fieldCount);
         fields.fill('');
          // for (var i=0;i<players.length;i++) {
          //   fields[i%4 >= 2 ? 1 : 0] += `${players[i].name}${i % 2 === 0 ? '\u200e' : '\n\u200f'}`;
          // }
          
          fields[0] = `**Island Residents:**\n`;
          for (var i=0;i<players.length;i++) {
            
            fields[(i+1)%fieldCount] += `${players[i].name} [${players[i].id}], ${players[i].identifiers[4]}`; 
          }
          for (var i=0;i<fields.length;i++) {
            let field = fields[i];
            if (field.length > 0) embed.addField('\u200b',`\n${fields[i]}`, true);
          }

        
        }
        sendOrUpdate(embed);
        LAST_COUNT = players.length;
      }).catch(offline);
    }).catch(offline);
    TICK_N++;
    if (TICK_N >= TICK_MAX) {
      TICK_N = 0;
    }
    for (var i=0;i<loop_callbacks.length;i++) {
      let callback = loop_callbacks.pop(0);
      callback();
    }
  };

Answer №1

If my understanding is correct, you are trying to retrieve the element from the identifiers array, but its position within the array is variable.

Fortunately, the element always begins with the word 'discord', allowing you to utilize the Array#find() method along with String#startsWith() to locate your discord ID. Below is an example snippet:

let players = [{
  id: 1,
  identifiers: ["license:57349756783645", "xbl:85437852", "live:8953291341", "discord:89325813521519", "fivem:893123"],
  name: "foo",
  ping: 56
}, {
  id: 2,
  identifiers: ["xbl:57420987", "live:09123489", "discord:86543932136453", "license:865496782134", "fivem:584723"],
  name: "bar",
  ping: 41
}, {
  id: 3,
  identifiers: ["live:99532945", "discord:80521578413532", "license:60795634523", "xbl:1239435", "fivem:943921"],
  name: "bar",
  ping: 41
}]

players.forEach(player => {
  let discord = player.identifiers.find(i => i.startsWith('discord')).replace('discord:', '')
  console.log(`
  ID: ${player.id}
  Name: ${player.name}
  Discord: ${discord}
  `)
})
// ...
fields[0] = `**Mieszkańcy na wyspie:**\n`;
for (var i = 0; i < players.length; i++) {
  const discord = players[i].identifiers.find((el) =>
    el.startsWith('discord'),
  ).replace('discord:', '');
  fields[
    (i + 1) % fieldCount
  ] += `${players[i].name} [${players[i].id}], ${discord}`;
}
// ...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issues with dynamically generating buttons using Ajax and Javascript technology

In order to dynamically create buttons based on the contents of a text file during the onload event, I have written a JavaScript function. However, despite being able to read the file and using alert messages to verify the correctness of the variable &apos ...

Make sure to look out for the x value or its equivalent when using AJAX in jQuery

Hey there, fellow developers! I'm working on an AJAX form for a registration process. The form sends data to a PHP file which then stores it in a database and returns a string like "success id:12345". I want the script to be able to parse JSON and ve ...

Tips for optimizing endless scroll implementation by consolidating multiple requests into a single AJAX call

Currently, I have a feature that loads every next 10 publications to the feed when the user scrolls to the bottom. The issue is that multiple AJAX requests are being sent because the code detects multiple scroll-to-bottom events. How can I modify it to o ...

Deciphering JSON using the jackson library

In my form, I use Jackson to parse parameters packed in JSON. However, when the parameter type is 'int' and a user inputs a large number, an exception occurs. While I have restricted this on the client-side, I'm trying to determine the best ...

Executing a complex xpath using Java Script Executor in Selenium WebDriver

When working with a large grid and trying to find an element using XPath, I encountered some difficulties. The XPath used was: By.xpath("//div[contains(text(),'" +EnteredCompetitionName+ "')]/preceding- sibling::div[contains(concat(' &apo ...

Selectize Fails to Populate Options Using Ajax

ExpressJS is the platform I am using to develop a management dashboard for a community project. Right now, my main concern is integrating a modal that allows users to add new games to a database. Although I am able to fetch data remotely, I am facing diffi ...

Encounters a fault while processing the php output

Displaying an error in the query The browser is showing the correct answer. $.ajax({ type: "POST", url: url, async: true, contentType: " charset=utf-8", dataType: "XMLHttpRequest", success: func ...

Ensuring the accuracy of user input in JavaScript, even after fixing a mistake and submitting again, will not cause the code to exit the else clause

I am currently working on a coupon code field that needs to accept a specific set of coupon keys. Below is the code I have written for validation. If a user enters an invalid key at first, they receive an alert saying "Invalid Key." However, if they corr ...

Why does getElementById work when getElementsByClassName doesn't?

I created a script with the purpose of hiding images one and two, while keeping image 3 visible and moving it into their place. The script functions correctly when using div Id's instead of div Classes. However, I prefer to use div classes for groupin ...

What is the best way to define a local variable with specific filters assigned to it?

I am working with an ng-repeat directive in the following manner: item in items | filter:myFilter | page:currentPage My goal is to determine the current count of items after applying the myFilter filter for pagination purposes. However, I found that foll ...

Webpack behaving strangely with inability to use 'import', while 'require' is functioning properly

I am facing a peculiar issue with webpack. Here is my configuration in webpack.config.js: import webpack from "webpack"; import path from "path"; //not working: import ExtractTextPlugin from "extract-text-webpack-plugin"; const ExtractTextPlugin = requi ...

Leveraging the back button in an AngularJS Mobile SPA

Utilizing AngularJS for my Single Page App (SPA), I am currently exploring the most effective way to handle the back button functionality on mobile devices. My setup involves a single JavaScript file, one HTML page, and no partials. The content is reveale ...

Ionic3 footer using ion-tabs

Is there a way to create a common footer for all pages with 5 buttons, where the first button is selected by default? The page opened by this first button should have three tabs. I have already created the tabs but am unsure how to add the footer without r ...

Issue with using Sinon FakeServer with Mocha

I'm currently in the process of setting up a test for an API call. In my attempt to create a fake server within the before method, I have encountered issues with testing the basic implementation using $.ajax compared to my actual api call. Strangely, ...

Setting the second tab as the primary active tab

I am currently working on a script that is well-known, and everything is functioning perfectly. However, I want to change it so that when the page is first opened, it displays the second tab instead of the first one (the first tab being a mail compose tab ...

The Angular TypeScript service encounters an undefined issue

Here is an example of my Angular TypeScript Interceptor: export module httpMock_interceptor { export class Interceptor { static $inject: string[] = ['$q']; constructor(public $q: ng.IQService) {} public request(config: any) ...

Discover the steps to retrieve a fresh array in PHP after utilizing sortable.js

Hi there! I am currently utilizing the sortable javascript feature found on Although the script is working perfectly fine for me, being a non-expert in javascript poses a challenge when it comes to generating the necessary code to retrieve an array in php ...

Is there a method `Object.values()` available in TypeScript?

How can I iterate through all values of an Object in TypeScript that I want to use for filtering another array? I have searched on Google and came across Object.values(), but it seems like it doesn't work in TypeScript. Is there an equivalent method ...

Endless loop JSON vulnerability

I recently came across a discussion on Stack Overflow about Google's practice of prepending while(1); to their JSON responses. Can anyone provide guidance on what type of PHP script would be suitable for this situation? I attempted the following: $ ...

The parental context is not bound to the isolated scope of the custom directive

Below is the custom directive implemented: (function() { angular.module('commentsDirective', []) .directive('mngComments', mngComments) function mngComments() { return { restrict: 'AE', ...