"NULL" value is added in array of localStorage - javascript

I'm using this code to add values to local storage:
rowSettings[counter] = [value1, value2, value3];
localStorage.setItem("rowSettings", JSON.stringify(rowSettings));
The result in the localStorage is then:
[null,[1,0,0],[1,0,0],[1,0,0],[1,0,0]].
So how come "null" is being added?
In Chome developer tool I get:
"Uncaught TypeError: Cannot read property '0' of null".
This happens when retrieving the objects back:
var row =0;
var retrievedObject = JSON.parse(localStorage.getItem('rowSettings'));
//Start each function
for (var i = 0; i < 3; i++) {
console.log(retrievedObject[row][i]);
}
row++;
//End each function

When you built rowSettings, you started (counter) at index 1 instead of 0. So the 0th element is null.
Answer found based on Jonathan's comment.

Related

set max input using looping compact in blade script laravel

I want to set max number from selected item. data max number from controller compact.
after i use select2 and datatables its cannot working. maybe I accidentally deleted an asset or something.
function max() {
var item_selected = document.getElementById("select").value;
var item= {!! json_encode($item->toArray(), JSON_HEX_TAG) !!};
//when i see the source
//var item= [{"id":1,"owned":1},{"id":2,"owned":10},{"id":3,"owned":12}];
for (i = 0; i<=item.length; i++){
//when i use console.log
//it still show id but the error moves to this with same error.
//console.log(item[i].id)
if (item[i].id==item_selected)
{
var input = document.getElementById("number");
input.setAttribute("max",item[i].owned);
}
}
}
the error part is if (item[i].id==item_selected)
and it said Uncaught TypeError: Cannot read property 'id' of undefined
for (i = 0; i<=owned.length; i++)
this line should be
for (i = 0; i<=item.length; i++)
side note: you can use a localized variable to avoid inlining blade within your javascript

Why can't I access the items of an array after they have been added?

I have this code:
var counter = 0;
var Index = {};
rows.forEach(function(element){
Index[counter] = element.data;
counter++;
});
And if I do Console.log(Index) it's displayed the right way in my console.
But I can't get to the data in this object. Things that don't work:
Index[3] //Undefined
Index["3"] //Undefined
Object.keys(Index) //Empty Array
The same happens if I use a Array and Array.push();
Index[3] // Undefined
Index.length // 0
Where is my error?
Screenshot from the console:
I think rows is coming from ajax request and you are doing your calculations before that promise comes. If we have more of that code it would be really nice.

Issue with object property '0' of undefined

My code yields the following error:
Uncaught TypeError: Cannot set property '0' of undefined
First, here's the screenshot of the table
Note:
This table are the assigned work schedule of the student.
Let's proceed to my code:
function saveWorkSched(){
// listWorkSched
var arr=[];
var getSAWorkSched=[[],[]];
var wsCounter=0;
var wsCounter2=0;
var j = 0;
$("#listWorkSched td").each(function(){
arr.push($(this).text());
});
console.log(arr);
for(j;j<arr.length;j++){
if(wsCounter2<=2){
getSAWorkSched[wsCounter][wsCounter2]=arr[j];
wsCounter2++;
}else{
wsCounter++;
wsCounter2=0;
getSAWorkSched[wsCounter][wsCounter2]=arr[j];
wsCounter2++;
}
}
}
1st phase:
after the user create the work schedule this will be stored in arr variable.
2nd phase:
the arr value will converted to multi-dimensional array and will be stored in getSAWorkSched variable
after the 3rd loop an error will occurred. it means that every time I create a work schedule more than 2 the error will trigger.
else{
wsCounter++;
wsCounter2=0;
getSAWorkSched[wsCounter][wsCounter2]=arr[j]; // Here's the code where the error specified based on the console of my browser
wsCounter2++;
}
You need to define the nested array that you try to access. It really comes down to the same principle: you address the following:
getSAWorkSched[wsCounter][wsCounter2]
... with a wsCounter value that is eventually getting to 2, but you have only defined two nested arrays in the initialisation of getSAWorkSched, so getSAWorkSched[2] does not exist -- it will give you undefined. Trying to get an array element from nothing (undefined) is not possible. So add this line before it in the else bock:
getSAWorkSched[wsCounter] = []; // <--- Add this
getSAWorkSched[wsCounter][wsCounter2]=arr[j];
More elegant code
You could use $.map and slice to write this in a more elegant way:
function saveWorkSched() {
var arr = $.map($("#listWorkSched td"), function (td) {
return $(td).text();
});
var getSAWorkSched = [];
for (var j = 0; j < arr.length; j += 3) {
getSAWorkSched.push(arr.slice(j, j + 3));
}
}

Javascript json array values

I have the following JSON:
{"title":"MYTITLE","employer":"MYEMPLOYER","weekends":[["6"],["8"],["15"]]}
I need to access weekends to get this:
6
8
15
Here is my try:
var json = $.parseJSON(data);
for (var i = 0, len = data.weekends.length; i < len; i++) {
console.log(data.weekends[i]);
}
But results are empty in chrome console log...if I understand correctly...i read length of json converted to an array and for in loop I read the value in the index array.
But I always get the error:
Uncaught TypeError: Cannot read property 'length' of undefined
Why is weekends length undefined? I set command length and it does not recognize it is an array and to count length so that for loop can work.
The problem is that you are accessing weekend using data, which is just raw JSON String. You need to access the json variable, which is the parsed JSON.
Below is the working code:
const data = {"title":"MYTITLE","employer":"MYEMPLOYER","weekends":[["6"],["8"],["15"]]};
// To avoid calculation of length on every iteration
const weekendLength = data.weekends.length;
for(let i = 0; i < weekendLength; i++){
console.log(data.weekends[i][0]);
}
Here, I am setting the JSON data directly to a variable. In your case, you are most probably getting the data from a network request. In that case, as you did in your code, you need to parse it first. (By calling $.parseJSON())
var data = {"title":"MYTITLE","employer":"MYEMPLOYER","weekends":[["6"],["8"],["15"]]};
for (var i = 0, len = data.weekends.length; i < len; i++){
console.log(data.weekends[i]);
}

How to check undefined variable javascript?

My Javascript is like this :
<script type="text/javascript">
var priceJson = '[{"#attributes":{"Code":"SGL","Total":"400000"},"DayPrice":{"Date":"2016-05-26","Rate":"400000"}},{"#attributes":{"Code":"DBL","Total":"200000"},"DayPrice":{"Date":"2016-05-26","Rate":"200000"}}]';
console.log(priceJson);
var priceObject = JSON.parse(priceJson);
console.log(priceObject);
if(priceObject.DayPrice.Rate)
priceObject = [priceObject];
else
priceObject = priceObject;
console.log(priceObject);
var priceJson = JSON.stringify(priceObject);
console.log(priceJson);
var countRoomType = priceObject.length;
for(var i=0; i<countRoomType; i++){
console.log(priceObject[i].DayPrice.Date);
console.log(priceObject[i].DayPrice.Rate);
}
</script>
Demo (See in console) : https://jsfiddle.net/oscar11/wsqdha8w/1/
Variable priceJson has a dynamic value. The value can be one single instance of data or can be an array of data. If the value contains 1 data then I convert into a data array like this:
if(priceObject.DayPrice.Rate)
priceObject = [priceObject];
But, in console there is the following error: TypeError: priceObject.DayPrice is undefined
Any solutions to solve my problem?
Judging by your error message, you need to check the existance of DayPrice also.
if( priceObject.DayPrice && priceObject.DayPrice.Rate )
This if condition has two steps.
First it checks if DayPrice exists,
Second it checks if DayPrice.Rate exists
It won't check second condition if first one fails

Categories