Pushing boolean value at a specific index in an array - javascript

I want to push a Boolean value at a specific index in an array. Whenever I ran the code I get this error, ERROR TypeError: Cannot read property 'push' of undefined
This is my code:
var check_ins = [];
for (var i = 0; i < this.employees.length; i++) {
// let check = check_ins[i];
if (check_ins[i] === true) {
let alert = this.alertCtrl.create({
title: 'Sorry,',
subTitle: 'ur already checked in',
buttons: ['OK']
});
alert.present();
break;
} else if (check_ins[i] === false || check_ins[i] === undefined) {
let checkInTime = new TimeInModel(in_timing.date, emp_id, in_timing.time_in);
this.employeesService.pushTimeIn(checkInTime)
.subscribe(checkInTime => {
},
error => this.errorMessage = <any>error);
console.log("Successfully checked-in!");
check_ins[i].push(true);
break;
}
What could be the problem? Is there another alternative to using an array to achieve the same output?

You don't need to push the value true into check_ins[i], you can just set it: check_ins[i] = true or push true to the array: check_ins.push(true)

When you use push, the pushed value gets added as a new element to the array. I suggest you do the following instead :
var check_ins = [];
for (var i = 0; i < this.employees.length; i++) {
// let check = check_ins[i];
if (check_ins[i] === true) {
let alert = this.alertCtrl.create({
title: 'Sorry,',
subTitle: 'ur already checked in',
buttons: ['OK']
});
alert.present();
break;
} else if (check_ins[i] === false || check_ins[i] === undefined) {
let checkInTime = new TimeInModel(in_timing.date, emp_id, in_timing.time_in, true);
this.employeesService.pushTimeIn(checkInTime)
.subscribe(checkInTime => {
},
error => this.errorMessage = <any>error);
console.log("Successfully checked-in!");
check_ins[i]=true;
break;
}

Related

Json TypeError: Cannot read properties of undefined (reading 'name')

I have an error where it says
TypeError: Cannot read properties of undefined (reading 'name')
I am making a Discord bot with NodeJS and Discord.js and I have an empty JSON where I add an item whenever I type a command but I can't get the values of that new item with the second I made I don't know why
{
"Scammere" : [
]
}
module.exports = {
name: 'addscammer',
description: "this is a ping command",
execute(message, args, Discord){
if(!args[0]) { return message.reply("Du skal skrive personens ingame navn"); }
if(message.member.roles.cache.has('850790004275019796') || message.member.roles.cache.has('850790306915942400')){
const jsonData= require('./test.json');
var playerIsNew = true;
for (let index = 0; index < jsonData.Scammere.length; index++) {
const element = jsonData.Scammere[index];
if(element.name.toUpperCase() == args[0].toString().toUpperCase()){
playerIsNew = false;
console.log("Person Findes Allerde");
}
}
var LocalStorage = require('node-localstorage').LocalStorage,
localStorage = new LocalStorage('./scratch');
index = 0;
for (let i = 0; i < jsonData.Scammere.length; i++) {
const element = jsonData.Scammere[i].name.toString();
if(element.toString().toUpperCase() == args[0].toUpperCase()){
index = i;
console.log(element + "is using" + i);
}else{
index = jsonData.Scammere.length + 1;
}
}
console.log(index);
if(jsonData.Scammere.at(index) != null){
console.log("Test");
playerIsNew = false;
}
if(playerIsNew){
var myObj = {
"name" : args[0],
"timesScamed" : 1,
"timesTrusted" : 0
};
jsonData.Scammere.push(myObj);
}else{
jsonData.Scammere.at(index).timesScamed = parseInt(localStorage.getItem("storedScams " + jsonData.Scammere.at(index).timesScamed));
jsonData.Scammere[index].timesScamed += 1;
}
console.log(jsonData.Scammere);
setTimeout(() => {
var hexColor = "#000";
var status = "scammer";
if(!playerIsNew){
if(jsonData.Scammere[index].timesScamed > jsonData.Scammere[index].timesTrusted){
hexColor = "#ff0000";
status = "Scammer"
}else{
hexColor = "#43eb34";
status = "Trusted";
}
}else{
hexColor = "#c4c4c4";
status = "MÃ¥ske";
}
const Test = new Discord.MessageEmbed().setColor(hexColor).setTitle("Data om: " + jsonData.Scammere[index].name.toString())
.setAuthor({ name: jsonData.Scammere[index].name.toString(), iconURL: 'https://minotar.net/avatar/' + jsonData.Scammere.at(index).name.toString() + '/128.png', url: 'https://discord.js.org' })
.setThumbnail('https://mc-heads.net/body/' + jsonData.Scammere.at(index).name.toString() + '/128.png')
.addFields(
{ name: 'Status', value: status },
{ name: 'Scammet', value: jsonData.Scammere.at(index).timesScamed.toString() },
{ name: 'Trusted', value: jsonData.Scammere.at(index).timesTrusted.toString() }
);
message.channel.send({ embeds: [Test] });
}, 500);
}
}
}
Your JSON of
{
"Scammere" : [
]
}
Is an object which has a single member called Scammere, which is an empty array.
Your
for (let index = 0; index < jsonData.Scammere.length; index++) {
loop will never enter its content because jsonData.Scammere is empty, which means that it has a length of 0 and (0 < 0) is false.
Yet, your line of
const Test = new Discord.MessageEmbed().setColor(hexColor).setTitle("Data om: " + jsonData.Scammere[index].name.toString())
expects jsonData.Scammere[index] to be an object that has a name field, but since jsonData.Scammere[index] does not exist, it is being evaluated to null and basically it turns out to be equivalent to null.name which throws your error.
Solution
If there is an item that you are not sure that it exists, then first check whether it exists and only if it does refer to its members/functions.

Angular - multiselect-dropdown - TypeError: Cannot read property 'length' of undefined

counter: number = 0;
getDatatypes(){
if(this.counter == 0) {
if(this.appId != 0)
{
if(undefined != this.datatypes && this.datatypes.length)
for (let i = 0; i < this.datatypes.length; i++) {
this.applicationDataType = new ApplicationDataType(this.route.snapshot.params.id, this.datatypes[i].dataTypeId, this.datatypes[i].description, false);
let datatype = this.checkedDatatypes.find(y => y.description === this.datatypes[i].description);
if (datatype) {
this.applicationDataType.checked = true;
this.applicationDataTypes.push(this.applicationDataType);
} else {
this.applicationDataType.checked = false;
this.applicationDataTypes.push(this.applicationDataType);
}
}
} else {
for(let i = 0; i < this.datatypes.length; i++){
this.applicationDataType = new ApplicationDataType(this.route.snapshot.params.id, this.datatypes[i].dataTypeId, this.datatypes[i].description, false);
this.applicationDataTypes.push(this.applicationDataType);
}
}
this.counter ++;
}
}
The line
if(undefined != this.datatypes && this.datatypes.length)
is the one giving the TypeError: Cannot read property 'length' of undefined.
This is the console error I am getting
These errors are not visible to the user and do not affect the functionality. I have tried everything, but the datatypes in the front end multi select-dropdown just keep disappearing. I have tried initializing datatypes: Datatype[] = [], wrapping my for loop with if(this.datatypes && this.datatypes.length), and using ?. These just make the multi select-dropdown empty when running the front end.
it seems like this.datatypes is not an array or its null ,you can simply ignore this error with ? .
Please Change this to if(this.datatypes?.length>0)
Can you please try as below. initialize dataTypes array, then replace for loop with forEach as below
counter: number = 0;
datatypes = [];
getDatatypes(){
if(this.counter == 0) {
if(this.appId != 0)
{
this.datatypes.forEach(dtype => {
this.applicationDataType = new ApplicationDataType(this.route.snapshot.params.id, dtype.dataTypeId, dtype.description, false);
let datatype = this.checkedDatatypes.find(y => y.description === dtype.description);
if (datatype) {
this.applicationDataType.checked = true;
this.applicationDataTypes.push(this.applicationDataType);
} else {
this.applicationDataType.checked = false;
this.applicationDataTypes.push(this.applicationDataType);
}
})
} else {
this.datatypes.forEach(dtype => {
this.applicationDataType = new ApplicationDataType(this.route.snapshot.params.id, dtype.dataTypeId, dtype.description, false);
this.applicationDataTypes.push(this.applicationDataType);
})
}
this.counter ++;
}
}

TypeError: Cannot read property 'description' of undefined

I am trying to make a discord bot. I would appreciate it, if someone could help me to solve this. I have been searching the whole internet, but I just can't solve it. As far as I investigated, they told me, that I have to define my embed or something like that. I tried to define it, but it still won't work. I get this error:
m.embeds[0].description === '**Cooldown**' && m.author.id === '555955826880413696'
^
TypeError: Cannot read property 'description' of undefined
My code:
let setHunt = new Set();
client.on('message', rmsg => {
var sw = rmsg.content.toLowerCase();
if (sw.startsWith('rpg hunt')) {
if (setHunt.has(rmsg.author.id)) {
return;
}
const rfilter = m => {
console.log(rmsg.content);
m.embeds[0].description === '**Cooldown**' && m.author.id === '555955826880413696'
};
const collector = rmsg.channel.createMessageCollector(rfilter, {
time: 2000,
max: 1
});
collector.on('end', m => {
if (m.size === 0) {
let filter = m => {
return m.id == '733786365342253087' || m.id == '733786293435105422' || m.id == '733786784336445461' || m.id == '733786616769937439';
}
let time;
let role = rmsg.guild.member(rmsg.author).roles.cache.find(filter);
if (typeof role == 'undefined') {
return
}
switch (role.id) {
case '733786365342253087': time = 60000; break;
case '733786293435105422': time = 54000; break;
case '733786784336445461': time = 48000; break;
case '733786616769937439': time = 39000; break;
}
setHunt.add(rmsg.author.id);
setTimeout(() => {
setHunt.delete(rmsg.author.id);
rmsg.channel.send(`Your **Hunt** is ready! <#${rmsg.author.id}>`);
}, time)
}
})
};
});

Uncaught TypeError: Cannot read property of undefined JSON

I'm working on pulling data from a json object and then displaying the information on the front end. What is the best way to wrap the code below to check to see if the variable SKU is undefined or unavailable then to not run the code at all.
On Google Chrome, I get an Uncaught TypeError: Cannot read property "dm" of undefined based on the code below.
var SKU = "556520000";
var dimBreak = obj[SKU]["dm"];
for(var i = 0; i < dimBreak.length; i++){
const dimAll = dimBreak[i];
let entries = Object.entries(dimAll);
for(const [prop, val] of entries) {
console.log(prop, val);
}
}
Thanks for your help.
Based on a comment below
I've tried below which gives same error as above.
var dimBreak = obj[SKU]["dm"];
console.log(dimBreak);
if(typeof dimBreak === 'undefined') {
console.log("Is undefined");
} else {
console.log("Is defined");
}
This code below however runs
var dimBreak = "Test";
console.log(dimBreak);
if(typeof dimBreak === 'undefined') {
console.log("Is undefined");
} else {
console.log("Is defined");
}
Object that is used
{
"556520000":{
"lmin":"35",
"dm":[
{
"Width":"147"
},
{
"Depth":"10"
},
{
"Height":"137"
}
],
"lmax":"68",
}
}
First you have to check SKU is present in the object, if not add a check. Your code seems to be working(You can see below)
var obj = {
"556520000":{
"lmin":"35",
"dm":[
{
"Width":"147"
},
{
"Depth":"10"
},
{
"Height":"137"
}
],
"lmax":"68",
}
}
var SKU = "556520000";
if(obj[SKU]){
var dimBreak = obj[SKU]["dm"];
for(var i = 0; i < dimBreak.length; i++){
const dimAll = dimBreak[i];
let entries = Object.entries(dimAll);
for(const [prop, val] of entries) {
console.log(prop, val);
}
}
} else {
console.log(SKU+' is not defined');
}

How do I iterate through all the id's?

Check out the api --> https://api.icndb.com/jokes/random/10
Everytime when the user clicks on a specific joke, it will be added to the favorite list.
To keep the code concise I will only show the function itself:
(function() {
"use strict";
const getJokesButton = document.getElementById('getData');
getJokesButton.addEventListener('click', getData);
loadLocalStorage();
function loadLocalStorage() {
let storage = JSON.parse(localStorage.getItem('favoList')) || [];
let listOfFavorites = document.getElementById("favorites");
let emptyArray = '';
if(storage.length > 0) {
for(let i = 0; i < storage.length; i++) {
let idNumberJoke = storage[i].id;
emptyArray +=
`<li><input type="checkbox" id='${idNumberJoke}'/> User title: ${storage[i].joke}</li>`;
listOfFavorites.innerHTML = emptyArray;
}
} else {
return false;
}
}
// fetch data from api
function getData() {
let listOfJokes = document.getElementById("list-of-jokes");
fetch('https://api.icndb.com/jokes/random/10')
.then(function(res) {
return res.json();
}).then(function(data) {
// variable is undefined because it is not initialized. Therefore at some empty single quotes
let result = '';
console.log(data.value);
data.value.forEach((joke) => {
result +=
`<li><input type="checkbox" class='inputCheckbox' id='${joke.id}'/> User title : ${joke.joke}</li>`;
listOfJokes.innerHTML = result;
});
bindCheckbox();
}).catch(function(err) {
console.log(err);
});
}
function clickedButton() {
getJokesButton.setAttribute('disabled', 'disabled');
getJokesButton.classList.add('opacity');
}
function bindCheckbox() {
let inputCheckbox = document.querySelectorAll('input[type=checkbox]');
let elems = document.getElementById('list-of-jokes').childNodes;
let favoriteList = document.getElementById('favorites');
let fav = JSON.parse(localStorage.getItem('favoList'))|| [];
if(elems.length > 0) {
inputCheckbox.forEach(function(element, index) {
inputCheckbox[index].addEventListener('change', function() {
let joke = this;
if(joke.checked && joke.parentNode.parentNode.id === 'list-of-jokes') {
joke.checked = false;
favoriteList.appendChild(joke.parentNode);
addFavorite(joke.id, joke.parentNode.innerText, fav);
}
if(joke.checked && joke.parentNode.parentNode.id === 'favorites') {
joke.checked = false;
removeFavorite(joke, index);
}
});
});
}
clickedButton();
}
function removeFavorite(favorite, index) {
let favoriteCheckBox = favorite;
let i = index;
// convert iterable object to an array, otherwise splice method would give an error.
let favoriteListItem = Array.from(favoriteCheckBox.parentNode);
favoriteListItem.splice(i, 1);
document.getElementById('list-of-jokes').appendChild(favorite.parentNode);
localStorage.setItem('favoList', JSON.stringify(favoriteListItem));
}
// store favorites in localStorage
function addFavorite(jokeId, jokeText, fav) {
let norrisJoke = {
id: jokeId,
joke: jokeText
};
let favorites = fav;
for (let i = 0; i < favorites.length; i++) {
if(favorites[i].id !== norrisJoke.id) {
favorites.push(norrisJoke);
}
}
// favorites[i].id !== norrisJoke.id
// always get the object before the push method and pass it into stringify
localStorage.setItem('favoList', JSON.stringify(favorites));
}
// function which will randomly add one joke to favorite list every 5 seconds
// function need a button which allows you to turn on and off this auto add function
})();
<div class="inner-body">
<button id="getData">GET Jokes</button>
<div class='inner-block'>
<h2>Chuck Norris Jokes</h2>
<ul class='unordered-list' id="list-of-jokes">
</ul>
</div>
<div class='inner-block'>
<h2>Favorites</h2>
<ul class='unordered-list' id="favorites">
</ul>
</div>
</div>
The keys and values would not be pushed into localStorage, the only thing I see is an empty [] in localStorage. The norrisJoke object literal will be dynamically changed. So how could I make this function works?
Too complex, but click on the link below and scroll down to the bottom:
https://codepen.io/chichichi/pen/Gyzzvb
You are trying to run through an empty list here
for (let i = 0; i < favorites.length; i++) {
if(favorites[i].id !== norrisJoke.id) {
favorites.push(norrisJoke);
}
}
This means that nothing will ever be pushed. You can reduce your list to an array of id, then check if the joke exists in the list.
const favIds = favorites.reduce((sum, element) => {
return sum.concat(element.id);
},
[]);
Now you can check if the joke doesn't exists in favorites
if(!favIds.includes(jokeId)){
favorites.push(norrisJoke);
}
The problem is the for loop, the first time it's executed favorites will be an empty array so it's length will be 0, so it will never enter the loop
Something like this should work:
favorites = favorites.filter(joke => joke.id !== norrisJoke.id).concat(norrisJoke);
let favorites = JSON.parse(localStorage.getItem('favoList'))|| {};
favorites[norrisJoke.id] =norrisJoke.joke
Why don't you use a map in place of an array?
Also as #fl9 points out your for loop will never start off! because favorites.length is 0 to begin with
But I want to check duplicates before the joke will be pushed into favorite list
By definition a hash will not allow duplicate entries, so no need to worry about duplications
Run localStorage.getItem('favoList') in the console of this fiddle :
(function() {
"use strict";
const getJokesButton = document.getElementById('getData');
getJokesButton.addEventListener('click', getData);
loadLocalStorage();
function loadLocalStorage() {
let storage = JSON.parse(localStorage.getItem('favoList')) || [];
let listOfFavorites = document.getElementById("favorites");
let emptyArray = '';
if(storage.length > 0) {
for(let i = 0; i < storage.length; i++) {
let idNumberJoke = storage[i].id;
emptyArray +=
`<li><input type="checkbox" id='${idNumberJoke}'/> User title: ${storage[i].joke}</li>`;
listOfFavorites.innerHTML = emptyArray;
}
} else {
return false;
}
}
// fetch data from api
function getData() {
let listOfJokes = document.getElementById("list-of-jokes");
fetch('https://api.icndb.com/jokes/random/10')
.then(function(res) {
return res.json();
}).then(function(data) {
// variable is undefined because it is not initialized. Therefore at some empty single quotes
let result = '';
console.log(data.value);
data.value.forEach((joke) => {
result +=
`<li><input type="checkbox" class='inputCheckbox' id='${joke.id}'/> User title : ${joke.joke}</li>`;
listOfJokes.innerHTML = result;
});
bindCheckbox();
}).catch(function(err) {
console.log(err);
});
}
function clickedButton() {
getJokesButton.setAttribute('disabled', 'disabled');
getJokesButton.classList.add('opacity');
}
function bindCheckbox() {
let inputCheckbox = document.querySelectorAll('input[type=checkbox]');
let elems = document.getElementById('list-of-jokes').childNodes;
let favoriteList = document.getElementById('favorites');
let fav = JSON.parse(localStorage.getItem('favoList'))|| [];
if(elems.length > 0) {
inputCheckbox.forEach(function(element, index) {
inputCheckbox[index].addEventListener('change', function() {
let joke = this;
if(joke.checked && joke.parentNode.parentNode.id === 'list-of-jokes') {
joke.checked = false;
favoriteList.appendChild(joke.parentNode);
addFavorite(joke.id, joke.parentNode.innerText, fav);
}
if(joke.checked && joke.parentNode.parentNode.id === 'favorites') {
joke.checked = false;
removeFavorite(joke, index);
}
});
});
}
clickedButton();
}
function removeFavorite(favorite, index) {
let favoriteCheckBox = favorite;
let i = index;
// convert iterable object to an array, otherwise splice method would give an error.
let favoriteListItem = Array.from(favoriteCheckBox.parentNode);
favoriteListItem.splice(i, 1);
document.getElementById('list-of-jokes').appendChild(favorite.parentNode);
localStorage.setItem('favoList', JSON.stringify(favoriteListItem));
}
// store favorites in localStorage
function addFavorite(jokeId, jokeText, fav) {
let norrisJoke = {
id: jokeId,
joke: jokeText
};
let favorites = fav;
for (let i = 0; i < favorites.length; i++) {
if(favorites[i].id !== norrisJoke.id) {
favorites.push(norrisJoke);
}
}
// favorites[i].id !== norrisJoke.id
// always get the object before the push method and pass it into stringify
localStorage.setItem('favoList', JSON.stringify(favorites));
}
// function which will randomly add one joke to favorite list every 5 seconds
// function need a button which allows you to turn on and off this auto add function
})();

Categories

Resources