Cannot add into an already initialized array - javascript

document.getElementById('form').addEventListener('submit', saveItem);
function saveItem(e){
var items= document.getElementById('items').value;
var date= document.getElementById('date').value;
var price= document.getElementById('price').value;
var expense= {
items: items,
date: date,
price: price
}
if(localStorage.getItem('bill')==null){
var bill=[];
bill.push(expense);
localStorage.setItem('bill', JSON.stringify(expense));
} else{
var bill = JSON.parse(localStorage.getItem('bill'));
bill.push(expense);
localStorage.setItem('bill', JSON.stringify(expense));
console.log(bill);
}
e.preventDefault();
}
there is no error if
if(localStorage.getItem('bill')==null)
but there comes error at else as
Uncaught TypeError: Cannot read property 'push' of undefined
at HTMLFormElement.saveItem
the data is stored when the local storage is empty but cannot add data if it is not.

Your expense is a object, you need to save the bill inside the local storage.
if(localStorage.getItem('bill')==null){
var bill=[];
bill.push(expense);
localStorage.setItem('bill', JSON.stringify(bill));
}

Can you please check what is the result of JSON.parse(localStorage.getItem('bill'));? Is its a valid array?

Related

AppLab error e.replace is not a function when reading from data set

function Checkout(Payment_Type, Tip_Amt){
var Cust_Order = [];
readRecords(Order_Data,{},function(Rec){
for (var i = 0; i < Rec.length; i++) {
appendItem(Cust_Order, Rec[i].Table);
appendItem(Cust_Order, Rec[i].Type);
appendItem(Cust_Order, Rec[i].Item);
appendItem(Cust_Order, Rec[i].Price);
}
console.log(Cust_Order);
});
}
This is part of a restaurant ordering app I have to build for uni. I've saved the customers order in a data set and now I wish to read from that dataset and get the order to be able to calculate the bill and produce an itemised bill
WARNING: Line: 176: readRecords() table parameter value ([object Object]) is not a string.ERROR: Line: 176: TypeError: e.replace is not a function. (In 'e.replace(m,"-")', 'e.replace' is undefined)
Well, for one, your code is really botched. The table name in readRecords isn't a string, and you don't actually need to loop through every entry in the bill to get everything. The returned records are formatted as an object.
function Checkout(Payment_Type, Tip_Amt){
var Cust_Order = [];
readRecords("Order_Data",{},function(Rec){
// Use Rec to get the bill after this line.
console.log(Rec);
}
});
}
From there, you could effectively give them an itemized bill. Just make sure that you clear the table each time you get a new customer.

local storage not identifying array name

I am trying to save an array of "items" in the cart. but when it goes on else section an error occur "Uncaught TypeError: Cannot read property 'items' of null" please help what's wrong with the code
var existing_cart = localStorage.getItem("cart");
existing_cart = JSON.parse(existing_cart);
console.log(existing_cart);
if (existing_cart.items instanceof Array) {
existing_cart.items.push({
'article_number': article_no,
'quantity': quantity,
'item_name ': item_name
});
console.log(existing_cart);
localStorage.setItem("cart", JSON.stringify(existing_cart));
} else {
var products = [{
'article_number': article_no,
'quantity': quantity,
'item_name ': item_name
}];
var cart = {
'items': products
}
localStorage.setItem("cart", JSON.stringify(cart));
toastr.success('Have fun storming the castle!', 'Miracle Max Says');
}
The first time you run the code there won't be anything in the local storage, so existing_cart will be null. You need to check for this.
Change
if (existing_cart.items instanceof Array) {
to:
if (existing_cart) {
var existing_cart = localStorage.getItem("cart") || '{"items":[]}';
In the case that it is the first time the code runs, the localStorage may not have the element, in which case it will return null or undefined. In that case you can default it to a JSON that will allow the logic to flow without encountering null pointer exceptions.

Value of objects inside objects that give undefined result

I'm new with JavaScript and I need to retrieve information stored in this way in a globally defined object.
var customMap ={
totalValues:{
total:10000
}
carPrices:{
'CAR1':{date1:price1}
'CAR2':{date2:price2}
}
}
It has been fed using a function and when I launch console.log(customMap) I can see the whole structure of it perfectly. The problem is when I try to retrieve specific information.
I always get undefined.
I have tried with:
for (var i in customMap.totalValues){
console.log(i);
console.log(customMap.totalValues[i]);
}//It doesn't write anything in the log.
console.log(customMap.totalValues["total"]);//undefined
console.log(customMap.totalValues.total);//undefined
what I have achieve is when I query it in this way:
console.log(customMap.totalValues);
//{}
//total: 10000
console.log(Object.values(customMap.totalValues));
console.log(Object.keys(customMap.totalValues));
console.log(Object.entries(customMap.totalValues));
All give same returning message:
//[]
//length: 0
Same happens with carPrices objects. I cannot retrieve information for each car. I mean CAR1, CAR2...
I've run out of ideas. I don't know if is because of the way of accessing to the object is not correct, or the object is not correctly defined or just because is globally declared.
I'd appreciate all ideas that you could have.
# Kirill Matrosov I add below the code to give an idea of my intention. As you may notice the object structure is bigger than the previous one because I try to be more precise in the issue. Anyway I have discovered that JS is not sequential and callbacks don't help me at all :S
var customMap =
{
totalValues:{},
carPrices:{}
}
function addValuesToCustomMap(date,car,value){
if (!customMap.carPrices[car]){
customMap.carPrices[car] = {
dates: {},
carTotalValue:0,
carPercent:0
};
}
if (!customMap.carPrices[car].dates[date]){
customMap.carPrices[car].dates[date] = value;
}
else if (customMap.carPrices[car].dates[date]){
var auxValue = customMap.carPrices[car].dates[date];
customMap.carPrices[car].dates[date] = auxValue + value;
}
var totalValue_byCar = customMap.carPrices[car].catTotalValue;
customMap.carPrices[car].catTotalValue = totalValue_byCar + value;
if(!customMap.totalValues["total"]){
customMap.totalValues["total"]=value;
}
else{
var tot = customMap.totalValues["total"];
customMap.totalValues["total"]=tot+value;
}
}
function calculatePercentagesByCar(){
var tot = customMap.totalValues["total"];
for (var k in Object.keys(customMap.carPrices)){
var totalCarPrice = customMap.carPrices[k].carTotalValue;
var percent = totalCarPrice*100/tot;
customMap.carPrices[k].carPercent = percent;
}
}
/*
customMap={
totalValue:{
total: xxxxxx
}
carPrices:{
'CAR 1': {
dates:{
{date1:value1},
(...)
{dateN:valueN}
}
carTotalValue: yyyyyy,
carPercent: zzzz
}
(...)
'CAR N': {(...)}
}
}
*/
var customMap ={
totalValues:{
total:10000
},
carPrices:{
'CAR1':{date1:'price1'},
'CAR2':{date2:'price2'}
}
};
console.log(customMap.totalValues.total);
console.log(customMap.carPrices.CAR1);
console.log(customMap.carPrices.CAR2);
Your object is broken.
var customMap ={
totalValues:{
total:10000
}, // here you are missing a comma.
carPrices:{
'CAR1':{date1:price1} // Is this value filled by the variable price1? If not is broken and should be 'price1'.
'CAR2':{date2:price2} // Is this value filled by the variable price2? If not is broken and should be 'price2'.
}
}
The problem might be that you forgot to separate the values in the customMap object and the carPrices property with commas.
Here's a working example of what you've tried
var customMap = {
totalValues:{
total:10000
},
carPrices:{
'CAR1':{'date1':'price1'},
'CAR2':{'date2':'price2'}
}
}
for (var i in customMap.totalValues){
console.log('property:', i);
console.log('value:', customMap.totalValues[i]);
}
/*
property: total
value: 10000
*/
console.log(customMap.totalValues["total"]);//10000
console.log(customMap.totalValues.total);//10000
console.log(customMap.totalValues);
console.log(Object.values(customMap.totalValues));
console.log(Object.keys(customMap.totalValues));
console.log(Object.entries(customMap.totalValues));

How to populate values in associative array javascript

sorry for my bad english
i am working in javascript and i have build an array i want to enter values in this array.
var attribute_sets = [];
$('.attribute_set :selected').each(function(i, selected){
attribute_sets[i]['id'] = $(selected).val(); // getting id
attribute_sets[i]['name'] = $(selected).text(); // getting name
});
Its giving me error
TypeError: attribute_sets[i] is undefined
also tried this one
attribute_sets[i]['id'].push($wk_jq(selected).val());
still getting same error
can any one please guide me how can i insert values in this JS array.
i want output like this
array
[0]
'id':'1',
'name':'abc'
[1]
'id':'2',
'name':'xyz'
try
$('.attribute_set :selected').each(function(i, selected){
attribute_sets.push({
id: $(selected).val(), // getting id
name: $(selected).text() // getting name
});
Use map() function.
attribute_sets = $('.attribute_set :selected').map(function(i, selected){
return {
'id' : $(this).val(),
'name' : $(this).text(),
}
}).get();

Chrome.storage wont store Array correctly

im working on a chrome extension and have problems with the chrome.storage api. I want to save a Array to the storage, the array gets stored, but not the values of the array. So array[x] is always 'null'. Code looks like this:
var storage = chrome.storage.local;
bookmarks = new Array();
var newButton = document.createElement('input');
//... Button properys are getting set
bookmarks[bookmarks.length] = newButton; //tried it also with .push()
var obj = {};
obj['bookmarks'] = bookmarks;
storage.set(obj, function(){ console.log('bookmark saved'); });
After restarting the extension and getting the storage via:
storage.get(null, function(result){
console.log('Storage: ', result);
});
the log looks like this:
Storage:
Object
bookmarks: Array[1]
0: null
length: 1
__proto__: Array[0]
__proto__: Object
Any suggestions whats going wrong and why the array isnt stored correctly?
Thanks!
To store an object in Chrome.storage, the object must be serializable. You can test whether or not an object is serializable, by attempting to JSON.stringify() it. If you try the following in your console:
JSON.stringify(document.createElement('input'));
You will see an error gets thrown - TypeError: Converting circular structure to JSON. Which means the object cannot be serialized, as it contains references to self.
Seeing as DOM elements cannot be serialized, and thus cannot be stored, a solution would be to create a new object, add the desired button properties to it, and store that instead:
bookmarks = new Array();
var newButton = document.createElement('input');
//... Button properties are getting set
var data = {
prop: newButton.prop
};
bookmarks.push(data);
storage.set({ bookmarks: bookmarks });
The newButton object is too complex to store. Instead you should store a primitive value. E.g. if you run the following the expected {bookmarks:[{foo:"bar"}]} can be retrieved from storage.local.
var storage = chrome.storage.local;
bookmarks = new Array();
bookmarks[bookmarks.length] = {foo:"bar"};
var obj = {};
obj['bookmarks'] = bookmarks;
storage.set(obj, function(){ console.log('bookmark saved'); });

Categories