Cannot read properties of undefined (reading 'answer') - discord.js

I'm trying to make a command whereas it fetches another bot's embed title and checks if it exists in my JSON file. In my code, I'm trying to get my bot answer a riddle by another bot.
This is what I'm trying to do:
This is my code (in the #456 bot):
const riddle = [
{
"riddle": "What has to be broken before you can use it?",
"answer": "egg"
},
{
"riddle": "I’m tall when I’m young, and I’m short when I’m old. What am I?",
"answer": "candle"
},
{
"riddle": "What month of the year has 28 days?",
"answer": "all of them"
},
{
"riddle": "What is full of holes but still holds water?",
"answer": "sponge"
},
{
"riddle": "What question can you never answer yes to?",
"answer": "Are you asleep yet?"
}
]
const id = args[0]
if (isNaN(id)) return;
const msg = await message.channel.messages.fetch(id);
if (!msg) return;
const answer = riddle.filter((obj) => obj.riddle === msg.embeds[0].title).answer
const emb = new MessageEmbed()
.setAuthor(msg.embeds[0].title)
.setDescription(msg.embeds[0].description)
.setColor(msg.embeds[0].color)
message.channel.send({content: `__**Answer:**__ ${answer}`, embeds: [emb]})
I get an error Cannot read properties of undefined (reading 'answer') whenever I try to run this code. I also tried separating the riddle to a JSON file before. It worked but it gave me an undefined answer. How do I fix this?

I simplified the case so you can study the filter, and understand the return behavior, as well as the output you want, which I show in the console.log:
const riddle = [
{
"riddle": "What has to be broken before you can use it?",
"answer": "egg"
},
{
"riddle": "I’m tall when I’m young, and I’m short when I’m old. What am I?",
"answer": "candle"
},
{
"riddle": "What month of the year has 28 days?",
"answer": "all of them"
},
{
"riddle": "What is full of holes but still holds water?",
"answer": "sponge"
},
{
"riddle": "What question can you never answer yes to?",
"answer": "Are you asleep yet?"
}
];
const msg = {
embeds:
[
{
title: 'What question can you never answer yes to?',
}
]
};
const answer = riddle.filter((obj) => obj.riddle === msg.embeds[0].title);
console.log(answer[0].answer);
you can make this more robust, but this will show you how the structures and filters work, which is your problem at hand.

Related

Creating threaded comment object from an array of comments with ancestors

I am working on a simple MERN app and I am trying to implement a nested comment section.
Currently I am able to create new comments and replies of comments. The resulting comment documents (see below) have a 'parents' field which is an array of the objectIds for the parent comments.
I can retrieve all comments associated with a post, filter the root comments and create a sorted list of the replies under each root comment.
I have a recursive React comment component built, but I am struggling to take the arrays and push the comments into an an array or object with a structure that allows me to then recursively render the comments in React.
// This is a sample document mongoDB document
{
"_id": { "$oid": "6292fa410809d3874a5d742d" },
"user": { "$oid": "6277297675616d3a21cbbf7a" },
"username": "whenInRome",
"list": { "$oid": "62816f570ebefe01c72dc3de" },
"listUser": { "$oid": "627598950839cf6d62e2ad85" },
"message": "You know, I really like Amatriciana myself!",
"parents": [
{ "$oid": "6291ce46aeb4a89ae4df8dac" },
{ "$oid": "6292fa410809d3874a5d742d" }
],
// And this is my code for manipulating the array of retrieved comment documents:
const { comments } = listContext;
const thread = [];
const rootComments = comments.filter((comment) => comment.parents.length < 2);
rootComments.forEach((rootComment) => {
const replies = comments
.filter((comment) => comment.parents[0] === rootComment.parents[0])
.sort((a, b) => b.parents.length - a.parents.length);
replies.forEach(reply => {
if (reply.parents.length > 1) {
let parentComment = reply.parents[reply.parents.length - 2];
Any suggestions for converting these sorted arrays into a structured comment thread would be really appreciated!
Thanks!

How to write a test for nested JSON response from enterprise application

I'm trying to use Postman as a test tool to validate that our customers all have a mailing address in our master system. I'm having trouble drilling down into the JSON due to its structure. Each response is an array structure with a single "node" that has no "head attribute" to address.
Example JSON:
[
{
"ID": "cmd_org_628733899",
"organization": {
"name": "FULL POTENTIAL",
"accountStatusCode": "1",
"accountStatusDescription": "OPEN"
},
"location": [
{
"locality": "LITTLE ROCK",
"locationType": "MAILING"
},
{
"locality": "BIG ROCK",
"locationType": "LOCATION"
}
]
}
]
Test code as it exists:
pm.test("Check for a Mailing Address", function () {
// Parse response body
var jsonData = pm.response.json();
// Find the array index for the MAILING Address
var mailingLocationIndex = jsonData.location.map(
function(filter) {
return location.locationType;
}
).indexOf('MAILING');
// Get the mailing location object by using the index calculated above
var mailingLocation = jsonData.location[mailingFilterIndex];
// Check that the mailing location exists
pm.expect(mailingLocation).to.exist;
});
Error message: TypeError: Cannot read property 'map' of undefined
I understand that I have to iterate to node(0) in the outer array and then drill into the nested location array to find an entry with a locationType = Mailing.
I can't get past the outer array. I'm new to JavaScript and JSON parsing - I am a COBOL programmer.
Knowing nothing else, I would say you mean this
pm.test("Check for a Mailing Address", function () {
var mailingLocations = pm.response.json().location.filter(function (item) {
return item.locationType === 'MAILING';
});
pm.expect(mailingLocations).to.have.lengthOf(1);
});
You want to filter out all the locations that have a MAILING type and there should be exactly one, or at least one, depending.
Whether pm.response.json() actually returns the object you show in your question is impossible to say from where I'm standing.
In modern JS, the above is shorter:
pm.test("Check for a Mailing Address", function () {
var mailingLocations = pm.response.json().location.filter(item => item.locationType === 'MAILING');
pm.expect(mailingLocations).to.have.lengthOf(1);
});

shuffling randomly objects/arrays in reactjs

i have a quiz questions set. i want to randomly pick 5 questions every time. any idea on how to do this.
this is the questions data
export const Quizdata = [
{
id: 0,
question:
"If you see this sign on a gate or farm entrance what should you do?",
options: [
"You should never enter the area where this sign is displayed",
"You can enter the area, if you know there is no bull present",
"Sometimes, these signs are wrong. So it is OK to enter if you take care",
"Most bulls are tame farm pets. You just have to take care"
],
answer: "You should never enter the area where this sign is displayed",
picture: <img src={Pic} id="pic1" alt="" />
},
{
id: 1,
question:
"If you see this symbol on a bottle or container what does it mean?",
options: [
"This symbol tells you that the contents of the bottle or container are hazardous and are very dangerous to humans and animals. You should not touch this bootle or container",
"This symbol is the logo or symbol for famous brands of chemicals",
"This symbol is the international symbol for weed killer spray",
"This symbol tells you that the contents of the bottle or container are hazardour and are very dangerous to animals only"
],
answer:
"This symbol tells you that the contents of the bottle or container are hazardous and are very dangerous to humans and animals. You should not touch this bootle or container",
picture: <img src={Pic2} alt="" id="pic2" />
},
{
id: 2,
question:
"If you see this symbol on a bottle or container what does it mean?",
options: [
"This symbol tells you that there is electricity flowing in a system",
"This symbol tells you that a machine has very dangerous blades or knives which can harm you",
"This symbol tells you that a food or liquid is out of date",
"This symbol tells you that this is a biological hazard and it is a serious threat to the health of all living things"
],
answer:
"This symbol tells you that this is a biological hazard and it is a serious threat to the health of all living things",
picture: <img src={Pic3} alt="" id="pic3" />
},
{
id: 3,
question: " Why should children not play with this piece of equipment?",
options: [
"It is a boring toy",
"This ratchet strap has many moving parts and it can cause damage to fingers and hands",
"This isn't a piece of farm machinery equipment",
"It doesn't work outside"
],
answer:
"This ratchet strap has many moving parts and it can cause damage to fingers and hands",
picture: <img src={Pic4} alt="" id="pic4" />
},
{
id: 4,
question:
"What age must you be in Ireland to drive a quad (all terrain vehicle) on a public road?",
options: ["21 years old", "12 years old", "14 years old", "16 years old"],
answer: "16 years old",
picture: <img src={Pic5} alt="" id="pic5" />
},
{
id: 5,
question: "what should you do?",
options: ["dont enter", "43", "all fine"],
answer: "43",
picture: ""
},
{
id: 6,
question: "what should you do?",
options: ["dont enter", "set", "all fine"],
answer: "set",
picture: ""
}
this is how i load in the quiz in the component did mount
loadQuiz = () => {
const { currentQuest } = this.state;
this.setState(() => {
return {
questions: Quizdata[currentQuest].question,
options: Quizdata[currentQuest].options,
answer: Quizdata[currentQuest].answer,
pictures: Quizdata[currentQuest].picture
};
});
console.log(this.state.answer);
};
i want it randomly pick 5 questions not repeated and display one by one. in this sandbox i have the working of how the existing questions load .https://codesandbox.io/s/reverent-saha-411y3
Try this logic but you need to ensure to take a copy of original array to another array so that your original set of questions are intact like this newQuestions = [...questions].
var myArray = [1,2,3,4,5,6,7,8,9,10];
var newArray = [];
for(let i=0; i<5; i++) {
let index = Math.floor(Math.random()*myArray.length);
newArray.push(myArray[index]);
myArray.splice(index, 1);
}
console.log(newArray);
Let me know if this helps.

Adding a movie to a user's list of favourites in MongoDB

I'm currently learning full-stack development and I'm having trouble on a task where I have to insert a movie ID into a users list of favourites using Mongodb.
The user I've created is:
{ "_id" : ObjectId("5e1501c6abeeaf482847d46e"),
"UserName": "JulijaDa",
"Password": "FwPreviledges",
"Email": "Julija.Da#live.ru",
"Birhday": {
"$date": "1995-03-16T00:00:00.000Z"
},
"Favs":[
{
"ObjectId": "5e1352793e9e6a804448db0c"
}
]
}
This user currently has only one favourite movie (5e1352793e9e6a804448db0c) and I need to add another (5e1352793e9e6a804448db0e) but, using this method:
db.user.update({
"UserName": "JulijaDa"
}, {
$push: {
"Favs": ObjectId("5e1352793e9e6a804448db0e")
}
})
Mongo returns:
WriteResult({ "nMatched" : 0, "nUpserted" : 0, "nModified" : 0 })
I'm following the instructions but, honestly, I'm starting to pull my hair out over here. Can someone tell me what I'm doing wrong? I can also provide more information if needed but, this is basically all I have right now!
Thank you in advance
Through a lot of trial and error, it seems the required code to add a favourite to his user in the database is:
db.[collection name].update(
{ _id: ObjectId("[ID of item being updated]") },
{ $push: { [Name of key]: { [value being added] } } }
)
In the above example, it would look like this:
db.users.update(
{ _id: ObjectId("5e1501c6abeeaf482847d46e") },
{ $push: { Favs: { ObjectId: "5e1352793e9e6a804448db0e" } } }
)
This will added the correct value to the correct fields.
I hope this helps other who are struggling too.

How add or delete an item from a tab in a hook?

I'm new with hooks and I would like to add or delete an item from my tab.
I don't know how to do it because this tab is an attribute of my hook tab.
const [questionResponses, setResponses] = useState(null);
I tried this fix but the syntax don't work :
setResponses( questionResponses[idQuestion].responses => [...questionResponses[idQuestion].responses,{
response_text: itemValue,
response_type: type,
}]);
I tried to use concat(), but it's freezing when the tab responses is not empty:
setResponses({
...questionResponses[idQuestion].responses, [idQuestion]: questionResponses[idQuestion]['responses'].concat([{
response_text: itemValue,
response_type: type,
}])
});
My tab have this structure:
[
{
"question_id": 1,
"question_text": "Best time of day",
"responses": [
{
"response_id": 33,
"response_text": "Morning",
"response_type": "radio"
}
]
},
{
"question_id": 2,
"question_text": "I heard about Marie-France Group via",
"responses": []
},...]
Could you help me please ? I don't know how to do it
Please see the code I added https://codesandbox.io/s/mystifying-liskov-quv5m.
Use spread operator for adding value in the existing array.
function addRespone() {
setResponses([...responses, { name: response }]);
}
For removal filter the exsiting array to remove the intended item.
function deleteResponse(itemIndex) {
const newResponses = responses.filter((item, index) => index !== itemIndex);
setResponses(newResponses);
}
Check codesandbox link for complete code.

Resources