toUpperCase not working in JavaScript with items in an object - javascript

I cant figure out why this is returning as an error.
item.Question.toUpperCase is not a function
I get this error in my expo application with react but no errors are thrown in the console
Error:
TypeError: item.Question.toUpperCase is not a function.
in item.Question.toUpperCase() item.Question.toUpperCase is undefined
I tried creating new variables as
var Question = item.Question.toUpperCase()
But that didn't seem to work so here is the full code
else if(item.Title == undefined){
const itemData = `${item.Question.toUpperCase()} ${item.answer.toUpperCase()} ${item.keyword.toUpperCase()}`;
const textData = search.toUpperCase();
return itemData.indexOf(textData) > -1;
item is an object in which Question is a string
Thank you
Edit:
So after some logging I found this area to be giving the error:
console.log(item.keyword,item.Title)
console.log(typeof item.Question, item.Question)
const itemData = `${item.Title.toUpperCase()} ${item.Question.toUpperCase()} ${item.answer.toUpperCase()} ${item.keyword.toUpperCase()}`;
const textData = search.toUpperCase();
console.log(typeof itemData,typeof textData)
when logging item.Question and the type I got number and NaN which is odd because from my database it should be pulling the string "this is a strng10"
All the other calls to the database seem to be working fine. They give the correct type for item.Question as String.
So I guess the problem I'm trying to solve is how the string is being converted to a number that is NaN?

This appears to work on my end. Are you certain you're passing the correct datatypes?
let item = {
Question: "test",
Title: undefined,
Answer: "thing",
Keyword: "wow"
}
if (item.Title === undefined) {
const itemData =
`${item.Question.toUpperCase()} ${item.Answer.toUpperCase()} ${item.Keyword.toUpperCase()}`
itemData
}
Console returns "TEST THING WOW"

So after logging all the way back to my call to the database I found an extra + before getting the question, removing that fixed the issue. So sorry for wasting all of your time.
The issuse was inside the object:
Question: + childData.Question

Related

How can I print an object in cy.log()?

Use case
This is a Cypress E2E test coded with JS and I'm trying to compare pre-production and production sitemap URL contents in order to find the differences. I have two data sets (fixture) one for production and the other for test env.
code snippet
let compareUrlsBetween = (prodSitemapUrls, testEnvSitemapUrls) => {
const pathFirstEnv = new Set(JSON.parse(prodSitemapUrls).map(url => (new URL(url)).pathname))
const pathSecondEnv = new Set(JSON.parse(testEnvSitemapUrls).map(url => (new URL(url)).pathname))
const diff = new Set(pathFirstEnv);
for (const path of pathSecondEnv) {
diff.delete(path);
}
return diff
}
// Check for differences
if (compareUrlsBetween.length > 0) {
let titi = typeof(compareUrlsBetween(prodSitemapUrls, testEnvSitemapUrls))
console.log(titi)
cy.log('text : ' , compareUrlsBetween (prodSitemapUrls, testEnvSitemapUrls)) // Returns null
//console.log(compareUrlsBetween(prodSitemapUrls, testEnvSitemapUrls))
//console.log('Production and test env sitemap urls are not ISO, ' + 'Here are the diffrences : ' , compareUrlsBetween (prodSitemapUrls, testEnvSitemapUrls))
//throw new Error()
} else {
expect(prodSitemapUrls).to.eq(testEnvSitemapUrls)
}
Test goal & the problem
Test goal is to fail the test in cas of diff between these two fixtures (.xml), throw a new error and show the diff as normal log (cy.log()). I've already tried multiple solutions like JSON.stringify(), data type convertion etc. but none of them solved my case.
Log I observe at this moment : logtext : , {}
PS : the other type of logs like console.log() or console.table() are working perfectly fine
Any help is much appreciated.
Solution
Convert the set into an array
cy.log('text : ' , [...compareUrlsBetween (prodSitemapUrls, testEnvSitemapUrls)])
Why?
I'm not 100% sure, but it seems like cy.log uses JSON.stringify underneath which causes sets to be converted to {}

API weather undefined. How do I create an IF statment in App Scripts

I downloaded a weather API to get the value of the current conditions, which all works well except for the alert "event" and "description".
If an "alert" exists I get the value, but when there is none, the result is "TypeError: Cannot read property '0' of undefined".
What I need is an IF statement that says "if undefined, "0" else get the value" for these two lines:
const alerts = resJSON["alerts"][0]["event"]
const alertDs = resJSON["alerts"][0]["description"]
You could use optional chaining
const resJSON = {alerts: [{notevent: "test", description: "my description"}]};
const alerts = resJSON?.alerts?.[0]?.event || "0";
const alertDs = resJSON?.alerts?.[0]?.description || "0";
console.log(alerts);
console.log(alertDs);

React Class method returns undef instead of a verified value

This question would seem basic but I'm stuck on this. I've got a class which is not a component, I used it to initialize a DB and do DB CRUD operations. The class has a method readMatrix which reads a dictionnary from a DB and returns it as a matrix. I can check the value of the matrix in the console and it is correct. However the value which is returned to the calling function is "undefined" instead of what I'm seeing in the console log. I tried to fix it with Redux/Hooks and found this way too complexe for a novice like me (I'm using functions/hooks as components, but a class for DB management).
Here's the code of the class:
readMatrix (r,c,id) {
const row = new Array(c).fill(null);
var tempMatrix=[];
for (let i=0; i<r; i++){
tempMatrix.push([...row])
}
var restaurantRef = app.database().ref("/restaurants");
restaurantRef.orderByKey().equalTo("1").on("child_added", function(snapshot){
// console.log(snapshot.child("/layout").val());
var restaurant=snapshot.child("/layout").val();
for (const [key, value] of Object.entries(restaurant)) {
let i=key;
for (const [rowkey, rowvalue] of Object.entries(value)){
let j=rowkey;
tempMatrix[i][j]=rowvalue;
}
}
console.log(tempMatrix);
return(tempMatrix);
});
}
And here's the calling function:
useEffect(()=>{
setMatrix(FirebaseClass.readMatrix(matrixHeight,matrixWidth, 1))
console.log(matrix);
}, []);
Any idea on what's wrong there ?
Thanks for the answer(s)
Here's the only think that fixed it.
Declare readMatrix as async.
Get the value in the matrix the following way:
FirebaseClass.readMatrix(matrixHeight,matrixWidth, 1).then(setMatrix)
Hope the answer is clearer than the question.

Javascript Equalize Element From Array

Guys I want to get an element from array. Here:
Follower:
{ follower:
[ 5edfe8f3bfc9d677005d55ca,
5edfe92fbfc9d677005d55cc,
5ee2326cc7351c5bb0b75f1a ],
user id:
5edfe92fbfc9d677005d55cc
The process:
if(follower == user){
console.log("sdasdsad")
}else{
console.log("no")
}
But when I do it it always returns as no.
Also this is the codes of===> Nodejs Follow System Not Working Properly
It is a nodejs project. So please look at the above link.
When I do
if(follower.includes(user)){
It gives the error of:
TypeError: Cannot read property 'includes' of null
And when I try to change some I get this error:
TypeError: takip.includes is not a function
Guys so thats why I say please look at the above code.
So how to equalize them?
As other peoples said earlier the follower itself is a property which its value is an array itself, so if you want to check whether an item exists within it or not you can check it with includes(), if it exists it will return true otherwise it will return false.
const follow = {
follower: ["5edfe8f3bfc9d677005d55ca",
"5edfe92fbfc9d677005d55cc",
"5ee2326cc7351c5bb0b75f1a"
]
}
const user = "5edfe92fbfc9d677005d55cc";
if (follow.follower.includes(user)) {
console.log("sdasdsad")
} else {
console.log("no")
}
But if you looking to find the exact position of the item within that array you can find it with indexOf(). If the item does not exist within the array it will return -1, otherwise, it will return the index of that item within the array.
const follow = {
follower: ["5edfe8f3bfc9d677005d55ca",
"5edfe92fbfc9d677005d55cc",
"5ee2326cc7351c5bb0b75f1a"
]
}
const user = "5edfe92fbfc9d677005d55cc";
console.log(follow.follower.indexOf(user));
You are trying to compare a string to an array so it will never pass the if statement.
If you change your if to be if ( follower.includes(user)) { then it will search the array for the string.
var follower = [
'5edfe8f3bfc9d677005d55ca',
'5edfe92fbfc9d677005d55cc',
'5ee2326cc7351c5bb0b75f1a'
]
var user = '5edfe92fbfc9d677005d55cc'
// This will always fail as follower is an array not a string
if (follower.includes(user)){
console.log("sdasdsad")
} else {
console.log("no")
}
References
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
Looks like follower is a property. You can use this solution:
objectName.follower.forEach(item =>
if (item == user) console.log(`${item} is the answer`);
);
This way, javascript will go through all of the elements in the array and print it out if it is matching with your user variable.
You can also use for loop or while loop for the same process, however, since you're using an array, forEach will be much more useful.
If this was not your question and I misunderstood your question, let me know, I'll see if I can help.
I hope this helps
var obj = {
follower: [ '5edfe8f3bfc9d677005d55ca',
'5edfe92fbfc9d677005d55cc',
'5ee2326cc7351c5bb0b75f1a'
]
};
var userId = '5edfe92fbfc9d677005d55cc';
function searchUser(object, user){
if(obj.follower.includes(user)){
return object.follower.filter(x => x == user);
} else {
return 'no';
}
};
console.log(searchUser(obj, userId));
You can use Array.protorype.some() to check if user exists in the follower array.
const obj = {
follower: [
"5edfe8f3bfc9d677005d55ca",
"5edfe92fbfc9d677005d55cc",
"5ee2326cc7351c5bb0b75f1a"
]
}
const user = "5edfe92fbfc9d677005d55cc";
if(obj.follower.some(item => item === user)) {
console.log("found")
} else{
console.log("no")
}
You can also get the item with Array.protorype.find() with the same way as above, just assign it to a variable
Array.prototype.some
Array.prototype.find

how to print a javascript object's elements

i am new to javascript and i currently have an object printed to console when i use the following code:
clickEvents: {
click:function(target) {
console.log(target);
}
}
when i view console i can see the following object:
i am banging my head against a wall to write code that takes the object and prints it to a div using the .append() method. i am extermely new to working with javascript objects, and would appreciate any help trying to tease out an object and/or print the object data.
is events the object name? would i tease out the eventDate using something like events->eventDate?
I've made this over ~15 minutes so it's imperfect; there are types and edge cases surely unaccounted for and the design of the function could be better - not to mention that performing all of this as a giant string and then setting that as HTML is likely bad practice (I'm used to React now, ha!). Regardless, this will iterate over any array or object you pass to it and print it all in a big <ul> recursively.
const targetEl = document.querySelector('.js-target')
if (!targetEl) return
// Small helper functions
const isObj = data => typeof data === 'object' && !Array.isArray(data) && data !== null
const isArr = data => Array.isArray(data)
const dataToHTML = (data, noNode = false) => {
if (isObj(data)) {
const accumulator = Object.entries(data).reduce((acc, set) => acc + `<li><strong>${set[0]}</strong>: ${dataToHTML(set[1], true)}</li>`, '')
return `<ul>${accumulator}</ul>`
}
else if (isArr(data)) {
const accumulator = data.reduce((acc, item) => acc + dataToHTML(item), '')
return `<ul>${accumulator}</ul>`
}
else return noNode ? data : `<li>${data}</li>`
}
const logHTML = dataToHTML(exampleData)
targetEl.innerHTML = logHTML
Assuming that your data/variable is named exampleData.
Any questions pop them in the comments :-)
I'm not sure if you have a div that you want to append to already, but you would do something like this ->
document.getElementById("toBeAppendedTo").innerHTML = target.events[0].eventDate; where toBeAppendedTo is the id of the div you're trying to add this text to.
append() is a jquery function, not a javascript function.
That won't have any formatting and will just be the string value 07-28-2017 in a div.

Categories

Resources