Sum object values - javascript

I'm trying to sum the values from the key "value" in the object data.
Googled alot but cant figure this out.
My guess is that i'm not retrieving the values from localStorage.
EDIT: And i want to save the summed values to localStorage...
var storage = localStorage.getItem("Bills");
if (storage !== null) {
var data = JSON.parse(storage);
loadData(data);
var id = data.length;
} else {
id = 0;
data = [];
};
function loadData(array) {
array.forEach(function(bill) {
newItem(bill.name, bill.value, bill.id, bill.payed);
});
};
function addBill() {
modal.style.display = "none";
var bill = document.getElementById("billName").value;
var billVal = document.getElementById("billValue").value;
newItem(bill, billVal, id, false);
data.push({
name: bill,
value: billVal,
id: id,
payed: false
});
billsTotals.innerHTML = Object.values(data).reduce((t, { value }) => t + value, 0); // ?????
localStorage.setItem("Bills", JSON.stringify(data));
};
function newItem(name, value, id, payed) {
if (payed == true) {
return;
}
var ul = document.getElementById("list");
var li = document.createElement("li");
li.appendChild(document.createTextNode(name + " " + value + "kr"));
li.setAttribute("id", id);
ul.appendChild(li);
bill = document.getElementById("billName").value = "";
billVal = document.getElementById("billValue").value = "";
};
i'v tried to add .values before reduce but nothing works:
billsTotals.innerHTML = Object.values(data.value).reduce((t, {value}) => t + value, 0); // ?????

Not sure about your data variable. But the data variable is an array then you could do something like this.
data.reduce((total,{value})=>{
return total +value
},0)

Related

How I can get object from another function

I'm trying to do a Shopping cart with HTML and JS. So I'm using (https://www.smashingmagazine.com/2019/08/shopping-cart-html5-web-storage/).
In my function save(), I have,
`function save(id, title, price) {
// var button = document.getElementById('button');
// button.onclick=function(){
// var test = localStorage.setItem('test', id);
window.location.href='/panier'
var obj = {
title: title,
price: price
};
localStorage.setItem(id, JSON.stringify(obj));
var test = localStorage.getItem(id);
var getObject = JSON.parse(test);
console.log(getObject.title);
console.log(getObject.price);
}`
so to get "title for example I don't have problem in my function save(), but in my function doShowAll(),
function CheckBrowser() {
if ('localStorage' in window && window['localStorage'] !== null) {
// We can use localStorage object to store data.
return true;
} else {
return false;
}
}
function doShowAll() {
if (CheckBrowser()) {
var key = "";
var id = localStorage.getItem(id);
var list = "<tr><th>Item</th><th>Value</th></tr>\n";
var i = 0;
//For a more advanced feature, you can set a cap on max items in the cart.
for (i = 0; i <= localStorage.length-1; i++) {
key = localStorage.key(i);
list += "<tr><td>" + key + "</td>\n<td>"
+ localStorage.getItem(key) + "</td></tr>\n";
}
//If no item exists in the cart.
if (list == "<tr><th>Item</th><th>Value</th></tr>\n") {
list += "<tr><td><i>empty</i></td>\n<td><i>empty</i></td></tr>\n";
}
//Bind the data to HTML table.
//You can use jQuery, too.
document.getElementById('list').innerHTML = list;
} else {
alert('Cannot save shopping list as your browser does not support HTML 5');
}
}
I can't to get my object.
I have tried:
if (CheckBrowser()) {
var key = "";
var id = localStorage.getItem(id);
var getObject = JSON.parse(test);
}
var list = "<tr><th>Item</th><th>Value</th></tr>\n";
var i = 0;
//For a more advanced feature, you can set a cap on max items in the cart.
for (i = 0; i <= localStorage.length-1; i++) {
key = localStorage.key(i);
list += "<tr><td>" + key + "</td>\n<td>" + getObject.title
+ localStorage.getItem(key) + "</td></tr>\n";
}
but when I add something else than key or localStorage.getItem(key) in "list +=" nothing is displayed in my html view.
So I just Want to display data from my object in the PHP array in doShowAll() function.
Hoping to have clear and wainting a reply. Thank you

Remove a specific item from localstorage with js

I am adding simple records to localstorage but I am having a hard time removing a specific item from my localstorage object. I am able to maintain the data on refresh and continue adding records no problem. I would like to add a button next to each entry that allows me to remove THAT particular record from localstorage and from my list.
How would I accomplish this given the code below?
var theLIst = document.getElementById('list');
var resetNotify = document.getElementById('reset-message');
var recordCounter = document.getElementById('record-counter');
var st = window.localStorage;
var count = st.clickcount;
var nameArray = [];
var newArr;
// Set the counter on refresh
if (JSON.parse(st.getItem('names'))) {
recordCounter.innerHTML = (count = JSON.parse(st.getItem('names')).length);
theLIst.innerHTML = st.getItem('names').replace(/[\[\\\],"]+/g, '');
} else {
recordCounter.innerHTML = (count = 0);
}
function addNameRecord() {
resetNotify.innerHTML = '';
var name = document.getElementById('names-field');
nameArray = JSON.parse(st.getItem('names'));
count = Number(count) + 1;
newArr = makeArr(nameArray);
// Check if there is anything in the name array.
if (nameArray != null) {
nameArray.push('<p class="name-entry"><strong>' + count + '. </strong> ' + name.value + '</p><button onclick="clearThisItem(\''+ name.value + '\')">Remove</button>');
} else {
nameArray = [];
nameArray.push('<p class="name-entry"><strong>' + count + '. </strong> ' + name.value + '</p><button onclick="clearThisItem(\''+ name.value + '\')">Remove</button>');
}
st.setItem("names", JSON.stringify(nameArray));
name.value = '';
if (!newArr[0]) {
count = 1;
theLIst.innerHTML = nameArray;
recordCounter.innerHTML = count;
} else {
theLIst.innerHTML = newArr[0].join('');
recordCounter.innerHTML = count;
}
}
// Take our string from local storage and turn it into an array we can use
function makeArr() {
return Array.from(arguments);
}
// Purge all entries, reset counter
function clearArray() {
st.clear();
nameArray = [];
theLIst.innerHTML = '';
recordCounter.innerHTML = (count = 0);
resetNotify.innerHTML = 'Array has been purged.';
}
Heres the code I tried
// Delete a specific entry
function clearThisItem(item) {
console.log(item);
localStorage.removeItem(item);
console.log(localStorage.removeItem(item))
return item;
}
Here is refactored code.
Firstly there is no need to store count, as we always have access to names.length
Store only names on localStorage, not entire HTML
For add and remove a name, fetch names array from localStorage, update it and save it back to localStorage.
After every action just update the UI using a single function call.
Note: Renamed names-field to name-field in the below implementation.
Here is the working code: https://jsbin.com/simitumadu/1/edit?html,js,output
var $list = document.getElementById('list');
var $resetMessage = document.getElementById('reset-message');
var $resetCouter = document.getElementById('record-counter');
var names = getNames();
if(names == null){
setNames([]); // initializing the empty array for first time.
}
renderData(); // display data
function addNameRecord() {
$resetMessage.innerHTML = '';
var name = document.getElementById('name-field');
addName(name.value);
renderData();
name.value = ''; //clear input field
}
function renderData(){
var names = getNames();
$resetCouter.innerText = names.length; // Count
var namesListHTML = '';
names.forEach(function(name, index){
namesListHTML = namesListHTML + '<p class="name-entry"><strong>' + (index + 1) + '. </strong> ' + name + '</p><button onclick="clearThisItem(\'' + name + '\')">Remove</button>'
});
$list.innerHTML = namesListHTML;
}
function clearArray() {
setNames([]); // clear names
$resetMessage.innerHTML = 'Array has been purged.';
renderData();
}
function clearThisItem(name){
removeName(name); // remove from localStorage
renderData();
}
function getNames(){
namesStr = localStorage.getItem('names');
if(namesStr) {
return JSON.parse(namesStr);
}
return null;
}
function setNames(names){
return localStorage.setItem('names', JSON.stringify(names));
}
function addName(name){
var names = getNames();
names.push(name);
setNames(names);
}
function removeName(name){
var names = getNames();
var index = names.indexOf(name);
if (index > -1) {
names.splice(index, 1);
}
setNames(names);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<p>Count : <span id="record-counter"></div></p>
<input id="name-field">
<button onclick="addNameRecord()">Add</button>
<button onclick="clearArray()">Clear</button>
<div id="list"></div>
<div id="reset-message"></div>
</body>
</html>
Use localStorage.removeItem(insertYourKeyHere); to remove an object from local storage.
For removing it from your nameArray you can search through your list for the record, set null and then sort your list by ensuring to move objects into new positions such that null is at the end, then decrement your count for the number of records

Get multiple values with local storage

I'd like to retrieve the name and the date of created tasks. I managed to put the value taskMessage in local storage, but I don't know how to add taskName as well. This is the code I currently have :
$(document).ready(function () {
var i = 0;
for (i = 0; i < localStorage.length; i++) {
var taskID = "task-" + i;
$('.task-container').append("<li class='item-content' id='" + taskID + "'>" + localStorage.getItem(taskID) + "</li>");
}
$('.floating-button').on('click', function () {
myApp.prompt('', 'Add Task', function (task) {
if (task !== "") {
myApp.prompt('', 'Choose time', function (time) {
var d1 = new Date();
d1.setHours(time, 0, 0, 0);
var hour = d1.getHours();
if (time > 0 && time < 25) {
var d2 = new Date();
var currenttime = d2.getHours();
if (time > currenttime) {
var taskID = "task-" + i;
var taskMessage = hour;
var taskName = task;
localStorage.setItem(taskID, taskMessage);
var newtask = '<li class="item-content ' + taskID + '"><div class="item-inner"><div class="item-title" >' + taskName + '</div><div class="item-after"> ' + taskMessage + ':00</div> </div></li>';
var taskitem = $('#' + taskID);
$('.task-container').append(newtask);
}
else {
myApp.addNotification({
message: 'Please choose a valide time period'
});
}
}
else {
myApp.addNotification({
message: 'Please choose a value between 1 and 24'
});
}
});
}
else {
myApp.addNotification({
message: 'Please enter a valid name'
});
}
});
});
});
First you should get the data into a variable
var getData =
{
"firstData":"data1",
"secondData":"data2",
"thirdData": "data3"
}
Then you can set the above data's in localStorage...
localStorage.setItem('dataKey', JSON.stringify(getData ));
Then get....
var val = localStorage.getItem('dataKey');
Enjoy!!!
If you want to store two different values in localStorage then you can do somrthing like this :
setItem in localStorage two times with different keys.
localStorage.setItem("message", taskMessage);
localStorage.setItem("name", taskName);
Store both the values in an object.
var obj = {
"message": taskMessage,
"name": taskName
}
var val = localStorage.setItem("task", obj);
typeof val: string
Value of val: [object Object]
setItem method convert the input to a string before storing it.
Try this :
// Put the object into storage
localStorage.setItem('task', JSON.stringify(obj));
// Retrieve the object from storage
var val = localStorage.getItem('obj');
console.log('retrievedValue: ', JSON.parse(val));
You can easily store values in localstorage using following example.
//Save the values to Localstorage
localStorage.setItem('first','firstvalue');
localStorage.setItem('second','secondvalue');
//Retrieve the values from localstorage
localStorage.getItem('first')
//"firstvalue"
localStorage.getItem('second')
//"secondvalue"
localStorage saves item key&value as string,so you call setItem with an object/json object,you must serialize json to string by JSON.stringify() method.when you get value you need parse string as json object using JSON.parse() method.
Test
test(`can't retrieve json from localStorage if raw json data saved`, () => {
localStorage.setItem('foo', {foo: 'bar'});
expect(localStorage.getItem('foo')).toEqual('[object Object]');
});
test(`retrieve json value as string from localStorage`, () => {
localStorage.setItem('foo', JSON.stringify({foo: 'bar'}));
let json = JSON.parse(localStorage.getItem('foo'));
expect(json.foo).toEqual('bar');
});
test(`key also be serialized`, () => {
localStorage.setItem({foo: 'bar'}, 'value');
expect(localStorage.getItem('[object Object]')).toEqual('value');
});
test('supports bracket access notation `[]`', () => {
localStorage.setItem('foo', 'bar');
expect(localStorage['foo']).toEqual('bar');
});
test('supports dot accessor notation `.`', () => {
localStorage.setItem('foo', 'bar');
expect(localStorage.foo).toEqual('bar');
});

Update JSON values with associated key

I am trying to collect the unique json data, I mean if the key exists the update its value. But not succeed to update the value of existing key.
var fpr_data = [{"rfr_id":"7","user_id":"5","fp_id":"10","raw_id":"3","raw_qty":"20.00","raw_wastage":"2","raw_name":"Buttons"},
{"rfr_id":"9","user_id":"5","fp_id":"10","raw_id":"4","raw_qty":"500.00","raw_wastage":"0","raw_name":"Yarn"},
{"rfr_id":"8","user_id":"5","fp_id":"10","raw_id":"5","raw_qty":"2.00","raw_wastage":"1","raw_name":"Needle"},
{"rfr_id":"7","user_id":"5","fp_id":"10","raw_id":"3","raw_qty":"20.00","raw_wastage":"2","raw_name":"Buttons"}];
var qty = 2, coll={}, _qty=0.00,_wastage=0.00;
// Filter and modify JSON data
$.each(fpr_data, function(i, data) {
_qty = data.raw_qty * qty;
_wastage = data.raw_wastage * qty;
// Next time add on existing keys
if( coll[data.raw_id] == data.raw_id ) {
var q = coll[data.raw_id].qty + _qty;
var w = coll[data.raw_id].wastage + _wastage;
coll[data.raw_id] = {"qty":q, "wastage":w};
}
else {
coll[data.raw_id] = {"qty":_qty, "wastage":_wastage};
}
});
console.log(coll);
In fpr_data there is raw_id that i want to collect unique ids and if the raw_id found in object then update its qty and wastage with raw_qty and raw_wastage. I got Unique JSON data but quantity and wastage are not getting update. What wrong i have done? You can find the same codes in fiddle and check the result in console.
Expected: The value of qty in 3 should be 80
JSFIDDLE
Below condition will not give you correct comparison, when object already exists in array.
if( coll[data.raw_id] == data.raw_id ) {
I think you should just do:
if(coll[data.raw_id]) {
If I understand you correctly try this example
if(coll[data.raw_id]) {
var q = coll[data.raw_id].qty + _qty;
var w = coll[data.raw_id].wastage + _wastage;
coll[data.raw_id] = {"qty":q, "wastage":w};
}
else {
coll[data.raw_id] = {"qty":_qty, "wastage":_wastage};
}
You use jQuery, so enjoy the jQuery.extend() function :
var fpr_data = [{"rfr_id":"7","user_id":"5","fp_id":"10","raw_id":"3","raw_qty":"20.00","raw_wastage":"2","raw_name":"Buttons"},{"rfr_id":"9","user_id":"5","fp_id":"10","raw_id":"4","raw_qty":"500.00","raw_wastage":"0","raw_name":"Yarn"},{"rfr_id":"8","user_id":"5","fp_id":"10","raw_id":"5","raw_qty":"2.00","raw_wastage":"1","raw_name":"Needle"}, {"rfr_id":"7","user_id":"5","fp_id":"10","raw_id":"3","raw_qty":"20.00","raw_wastage":"2","raw_name":"Buttons"}];
console.log(fpr_data);
var qty = 2, coll={}, _qty=0.00,_wastage=0.00;
// Filter and modify JSON data
$.each(fpr_data, function(i, data) {
_qty = data.raw_qty * qty;
_wastage = data.raw_wastage * qty;
// Next time add on existing keys
var currentObj = coll[data.raw_id]; // Try not to repeat yourself ;-)
if( currentObj == data.raw_id ) {
var q = currentObj.qty + _qty;
var w = currentObj.wastage + _wastage;
console.log(data);
coll[data.raw_id] = $.extend(data, {"qty":q, "wastage":w});
}
else {
coll[data.raw_id] = $.extend(data, {"qty":_qty, "wastage":_wastage});
}
});
console.log(coll);
I hope this is what you were looking for.

How to dymically update object on input change?

I have a input tab that I want to update dynamically. When the user changes the value of the input, the new value should replace the old value of the object inside the array.
I am way off the mark here. Can somebody help me out.
function Skills () {
var Skills = this;
this.skill = new Array();
this.skill[0] = {
id: '1_skill_field',
value: 'Insert Skill',
//change function to be used when user changes the value.
change:function (input) {
Skills.skill[parseInt(input.id)["value"]=$("#"+input.id).val();
}
}
var create_section_field = function () {
var section_field = $('<div class="section_fields"></div>');
section_field.appendTo('#skill');
}
var create_fields = function () {
var input_field = $('<div class="input_fields"></div>');
input_field.appendTo('#skill .section_fields');
var skill_field=$('<input>', {
name: '1_skill_field',
id: Skills.skill[0]["id"],
value: Skills.skill[0]["value"],
type: 'text',
//onChange uses function to change saved value of object inside array
onChange: Skills.skill[0].change(this)
});
skill_field.appendTo($('#skill .input_fields'));
}
}
i made what you were doing...here take a look:
http://jsfiddle.net/V4HLz/1/
it was kinda fun. :D
var type = $('#type'),
input = $('#input'),
btn = $('#update'),
show = $('#out'),
stats = $('.skills');
var value, sType, skills={};
btn.click(function(){
value = parseFloat(input.val().trim());
sType = type.val();
if (!value || !sType) return;
skills.update(sType,value);
updateInput();
});
type.change(updateInput);
function updateInput() {
input.val(skills.data[type.val()]);
}
skills.update = function(t,v){ this.data[t] = v; };
skills.data = {
eating:0,
fighting:0,
flying:0,
reg:0
};
show.click(function(){
$.each( skills.data, function(k,v){
stats.find('#'+k).children('span').text(v);
});
});

Categories