Skip to content Skip to sidebar Skip to footer

How Can I Import Only Discord From Json File?

I've got an array of objects, these objects have an identifiers array with strings. One of these strings contains a Discord ID. The problem is its position is changing all the time

Solution 1:

If I understand you correctly, you want to get the element from the identifiers array, but its position is not fixed, it can be anywhere.

Luckily, the element always start with the word 'discord', so you can use Array#find() with String#startsWith() to find your discord ID. Check out the snippet below:

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}`;
}
// ...

Post a Comment for "How Can I Import Only Discord From Json File?"