Discord.js outputting an entire array but want to add an emoji to correspond with each object - discord.js

I am writing Guild Wars 2 commands into my bot and I have a wallet command which looks up ID's against an endpoint to give each ID a name. What I would like to do is instead of just displaying the name, I would like to display an emoji of each thing. For example, karma symbol for karma, gem symbol for gems. Adding emojis is easy, I get that part, however I can't wrap my head around how to identify what each line in the output is going to be as it is different per account that is looked up.
Here is my code so far:
var newArray = [];
for (var i = 0; i < walletArray.length; i++) {
for (var x = 0; x < currencyArray.length; x++) {
if (walletArray[i].id === currencyArray[x].id) {
if (currencyArray[x].name === "Coin") {
var bronze = String(walletArray[i].value).slice(-2)
var silver = String(walletArray[i].value).slice(-4, -2)
var gold = String(walletArray[i].value).slice(0, -4)
}
newArray.push(`${currencyArray[x].name} - ${walletArray[i].value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`)
}
}
}
The walletArray (or part of it) is:
[
{
"id": 1,
"value": 57636
},
{
"id": 2,
"value": 32969
},
{
"id": 3,
"value": 36
}
]
The currencyArray is:
{
"id": 1,
"name": "Coin",
"description": "The primary currency of Tyria. Spent at vendors throughout the world.",
"order": 101,
"icon": "https://render.guildwars2.com/file/98457F504BA2FAC8457F532C4B30EDC23929ACF9/619316.png"
},
{
"id": 2,
"name": "Karma",
"description": "Earned through various activities. Spent at vendors throughout the world.",
"order": 102,
"icon": "https://render.guildwars2.com/file/94953FA23D3E0D23559624015DFEA4CFAA07F0E5/155026.png"
},
{
"id": 3,
"name": "Laurel",
"description": "Earned through the Log-in Reward Chest. Spent in major cities. Used to purchase various rewards.",
"order": 104,
"icon": "https://render.guildwars2.com/file/A1BD345AD9192C3A585BE2F6CB0617C5A797A1E2/619317.png"
}
The output is:
Wallet command output
I have no idea if I am even approaching this correctly but I just want it to look a bit nicer! It is fully functional just we can always improve things. My JS is not the best, it was learned during lockdown as something to do and was learned almost entirely from this website!
Any help would be appreciated, cheers.

Well, if I understand your problem correctly, you know each line of the output is gonna be, because of currencyArray.name. The solution should be something like:
var newArray = [];
for (var i = 0; i < walletArray.length; i++) {
for (var x = 0; x < currencyArray.length; x++) {
if (walletArray[i].id === currencyArray[x].id) {
var emote;
if (currencyArray[x].name === "Coin") {
emote = "🪙"
var bronze = String(walletArray[i].value).slice(-2)
var silver = String(walletArray[i].value).slice(-4, -2)
var gold = String(walletArray[i].value).slice(0, -4)
}
else if (currencyArray[x].name === "Karma") {
emote = "☯️"
}
else if (currencyArray[x].name === "Laurel") {
emote = "💳"
}
newArray.push(`${emote} ${currencyArray[x].name} - ${walletArray[i].value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`)
}
}
}
Of course, use any emotes you wish.

Maybe you want to use a Map. discord.js names it Collection but they are pretty much the same.
let myMap = new Map();
myMap.set('key', 'emoji')
let emoji1 = myMap.get('key') //'emoji'
The 'key' is linked to the value which you can get with the Map.get method

Related

how to make slots output different responses

Doing some smart home skill development and my Intent utterance is "how long until my battery is {state}" State being either empty or full. I know I could do this with different intents but I wont want to have two many intents as I already have many. I basically want the user to say either full or empty in place of {state}. and then from there, depending on their answer, give different answers for full or empty. I haven't found much online so i hope you guys can help. Im also new to code.
You should create a slot for your battery state:
{
"name": "BatteryState",
"values": [
{
"id": "empty",
"name": {
"value": "empty"
}
},
{
"id": "full",
"name": {
"value": "full"
}
}
]
}
You can create it by yourself in the UI or paste in types collection in JSON editor.
Then use created slot in your intent
{
"name": "BatteryStateIntent",
"slots": [
{
"name": "batteryState",
"type": "BatteryState"
}
],
"samples": [
"how long until my battery is {batteryState}"
]
}
You can create it by yourself in the UI or paste in intents collection in JSON editor.
Then in the code:
const BatteryStateIntentHandler = {
canHandle(handlerInput) {
return (
Alexa.getRequestType(handlerInput.requestEnvelope) === "IntentRequest" &&
Alexa.getIntentName(handlerInput.requestEnvelope) === "BatteryStateIntent"
);
},
handle(handlerInput) {
const batteryStatus =
handlerInput.requestEnvelope.request.intent.slots.batteryState.value;
let speakOutput = "";
if (batteryStatus === "full") {
const timeToFull = 10; // or some sophisticated calculations ;)
speakOutput += `Your battery will be full in ${timeToFull} minutes!`;
} else if (batteryStatus === "empty") {
const timeToEmpty = 5; // or some sophisticated calculations ;)
speakOutput += `Your battery will be full in ${timeToEmpty} minutes!`;
} else {
speakOutput += "I don't know this status";
}
return handlerInput.responseBuilder
.speak(speakOutput)
.reprompt(speakOutput)
.getResponse();
},
};
Make sure you used the same intent name as in the builder. And at the end, add created intent handler to request handlers:
exports.handler = Alexa.SkillBuilders.custom()
.addRequestHandlers(
BatteryStateIntentHandler,
// ...
)
.lambda();

ReactJS ES6 array filtering

I'm trying to group data from an object to a multidimensional array
In the last three days I've tried multiple ways to get the result I want. Since I've no luck, probably because of my poor knowledge of ReactJS/ES6. I hope someone can explain how I can get this to work.
I think I'll have to use the map function. Within the map function, a filter function to get the unique companies and then a loop to add the table information.
The end result should be like this: https://wireframe.cc/No5uB7
The data I'd like to filter:
{
"viewings": [
{
"companyXXX": "company-XXX",
"time_start": "02/04/2019",
"time_end": "03/04/2019 11:59"
},
{
"companyXXX": "company-XXX",
"time_start": "14/04/2019",
"time_end": "15/04/2019 11:59"
},
{
"companyYYY": "company-YYY",
"rejection": 40,
"time_start": "14/04/2019",
"time_end": "15/04/2019 11:59"
}
]
}
The code I still have that isn't working
genData(data) {
const di = data.viewings;
let mps = [];
di.map(m => mps.push(m.company));
mps = Array.from(new Set(mps));
console.log( mps );
let mps = [];
di.map((m) =>
console.log( di.filter(mps => m.company) )
);
}
I might help if your input data was a bit more consistent, especially since you're trying to write m.company, which won't mean anything unless there is a company object in each viewing.
{
"viewings": [
{
"company": "company-XXX",
"time_start": "02/04/2019",
"time_end": "03/04/2019 11:59"
},
{
"company": "company-XXX",
"time_start": "14/04/2019",
"time_end": "15/04/2019 11:59"
},
{
"company": "company-YYY",
"time_start": "14/04/2019",
"time_end": "15/04/2019 11:59"
}
]
}
Then you can write:
var viewings = data.viewings.
var firstViewing = viewings[0];
var firstCompany = firstViewing.company;
var firstTimeStart = firstViewing.time_start;
// etc...
Your input data should be more structured to begin with.
Then you can log out each company name:
var viewings = data.viewings;
viewings.forEach(v => {
console.log(v.company);
});
You mention JSX in your question, but there's no JSX code. This appears to be an issue with your knowledge of JS rather than JSX.

Angular 6 compare two JSON Arrays

I am fetching notifications using API. Now here is the scenario:
1- I called the API, got 2 records and stored them in local variable (notifications) to show in view.
[{"id": 1, "notification": "bla"}, {"id": 2, "notification": "bla bla"}]
2- I am calling the same API to check for new notification after every 5 seconds. This time I need to compare the API response with the local variable, so if no new notification (different id) is in the record, don't push in local variable, other push.
I have tried something like this:
var val = JSON.parse(data);
if( val.length > 0 ) {
for( var i = 0; i < val.length; i++ ) {
this.notifications.forEach(element => {
if( element.id != val[i].id ) {
this.notifications.push(val[i]);
}
});
}
}
But its adding duplicate records. Any help would be appreciated.
Thanks
You need to use Array.find() to find the duplicate object in the val array.
var notifications = [{"id": 1, "notification": "bla"}, {"id": 2, "notification": "bla bla"}];
var data = `[{"id": 1, "notification": "bla"}, {"id": 4, "notification": "bla bla bla"}]`
var val = JSON.parse(data);
if( val.length > 0 ) {
val.forEach((obj)=>{
var existNotification = notifications.find(({id}) => obj.id === id);
if(!existNotification){
notifications.push(obj);
}
});
}
console.log(notifications);
Currently, you are getting duplicated element because the id value is compared against all the existing id values in notifications array. So, if one of the id do not match with another, it is pushed immediately into the notifications array. So, the better way and simple way is to use a find operation on the array to check the existing object.
A more robust way to handle this could be by using map in JS.
Rather than iterating the notifications (size = m) for every object in the data (size = n) would result in more time complexity of O(m x n).
Hence it could be done in O(n) as below:-
var notifications = new Map();
// assuming you get this at the beginning
var data1 = `[{"id": 1, "notification": "bla"}, {"id": 2, "notification": "bla bla"}]`;
checkAndAddNotification(data1);
// assuming you get this at the second time
var data2 = `[{"id": 1, "notification": "bla"}, {"id": 4, "notification": "bla bla bla"}]`
checkAndAddNotification(data2);
function checkAndAddNotification(data){
var val = JSON.parse(data);
if (val){
val.forEach((obj)=>{
var existNotification = notifications.get(obj.id);
if(!existNotification){
notifications.set(obj.id, obj);
}
});
}
}
console.log(notifications);
notifications.forEach((notification) => console.log(notification));
Please open the browser console as well while running the code.
Even if you plan to iterate over the map, the order would be preserved in the order the objects were inserted. Please look here for more.

How to push some data from Json into new array in AngularJS?

Let's say I have this Json ..
{
"name": "Mark",
"gender": "male",
"account1": {
"accountNo": 1201,
"balance": 300
},
"account2": {
"accountNo": 1354,
"balance": 5000
}
}
What I expect is like ..
$scope.myArray = [
{
"accountNo": 1201,
"balance": 300
},
{
"accountNo": 1354,
"balance": 5000
}
];
In AngularJS, how can I pick some part of Json data and push it into an array iteratively( I mean, when I have account1, account2 account3 or more, it can still add them into the array).
You could normally just assign the array over, but in this scenario that is not an option because your array is psuedo.
Ideally you would like to be able to do what this answer (related question) does: How to return and array inside a JSON object in Angular.js which is simply
$scope.myArray = json.accounts;
However, as noted, you do not have an accounts array so you need to make one.
var accounts = [];
for(var key in json){
if( !json.hasOwnProperty(key) // skip prototype extensions
|| !json[key].hasOwnProperty("accountNo") //skip non account objects
) continue;
accounts.push(json[key]);
}
And now you may use this array
$scope.myArray = accounts;
You can access Json data like an array. Like var foo = { ... , 'bar' = 'value', ... } you could get foo value by doing this for['bar']. So, by knowing this, you simply do something like
var arr = [];
for (var i = 0; i < 10; i++) {
arr.push(foo['account'+i]);
}
Although, this has nothing to do with angularjs.

getColumnArray equivalent for parsed JSON object arrays in Smartface.io Framework?

I got a Json file like;
{
"Cities": [
{
"Name": "London",
"Country": "UK"
},
{
"Name": "Rome",
"Country": "ITA"
},
{
"Name": "Antalya",
"Country": "TR"
}
]
}
How can I get City Names as an array like ["London","Rome","Antalya"] without doing;
var tempJSON = JSON.parse(jsonCities);
var arrayCityNames = [];
for (var i = 0; i < tempJSON.Table.length; i++){
arrayCityNames[i] = tempJSON.Table[i].Name;
}
if tempJSON was a Dataset we could use getColumnArray
arrayCityNames = Data.Dataset.getColumnArray("Name");
Is there any built in method to do this for parsed JSON's?
Please keep in mind that the question is related to Smartface.io Framework, not jquery itself
Try this:
var tempJSON = JSON.parse(jsonCities);// here you load your JSON
var arrayCityNames = []; // your output array
var cityArray = tempJSON['Cities']; // enter Cities array
for (var i = 0; i <cityArray.length; i++){ // iterate over your list
arrayCityNames.push(cityArray[i]['Name']); // add to list name of your city list
}

Resources