I want to create if the value is 0 and update if the value is 1.
So I wrote this one,
var juiceCart = [{
'name': val,
'count': unTouch
}];
if (value == 0) {
console.log('create cookie');
$.cookie("juiceCart", JSON.stringify(juiceCart));
doDummyCall();
} else {
console.log('update cookie');
$.cookie("juiceCart", JSON.stringify(juiceCart));
doDummyCall();
}
Inside the doDummyCall()
I am just doing a ajax call to update the headers and
var cookieJuiceCart = $.parseJSON($.cookie("juiceCart"));
$.each(cookieJuiceCart, function (index, value) {
console.log('Id : ' + value.name);
console.log('Value : ' + value.count);
});
and then printing the cookie in each function to know all the items present in it.
If i add the first item, it is printing
Id : 1
Value : 1
Then, if i add the Second item it is printing
Id : 2
Value : 1
But what i expect is
Id : 1
Value : 1
Id : 2
Value : 1
I know that the old value is replaced because i am not pushing the value in it.
So, I did
juiceCart.push({'name': val, 'count': unTouch});
But it is just replacing the old value with new one.
How can i check the existence of old value inside the array and create or update according to it.
The actual problem seems to me is your array:
var juiceCart = [{
'name': val,
'count': unTouch
}];
which is using vars to update same object instead of pushing new object.
You can do this:
var juiceCart = $.parseJSON($.cookie("juiceCart")) || []; // create a blank array taken from #apokryfos's answer.
juiceCart.push({'name': val, 'count': unTouch}); // <---now push it here.
This way you are able to push new object each time you call it.
This is what I got from the question. It's a bit poorly explained so I may not have understood what you need to do.
var juiceCart = $.parseJSON($.cookie("juiceCart")) || [];
var newItem = true;
juiceCart.each(function (i, v) {
if (v.name == val) { v.count++; newItem = false; }
});
if (newItem) {
juiceCart.push({'name': val, 'count': unTouch});
}
$.cookie("juiceCart", JSON.stringify(juiceCart));
doDummyCall();
Related
I have a few inputs with data attribute and value. I want to get data attribute for key and for value to get value from input. And where the value repeats it to be recorded only once.
Here is my demo https://jsfiddle.net/7L3eugqp/.
The result that I want should be look like that:
"A_1_1": {1, 2, 3},
"A_1_2": {4, 5, 6}
I will be grateful if someone give me advice how to do this. Thanks.
You were overriding the first dataset each time your loop found another element.
var datasets = {};
$('.project').each(function(index, value) {
catName = $(this).data("prefix");
datasets[catName] = datasets[catName] || {
label : catName,
data: []
};
datasets[catName].data.push($(this).val());
});
console.log(datasets);
If you don't want to have 1 twice (treat them as distinct sets), you can enclose the push call in this if statement:
if (datasets[catName].data.indexOf($(this).val()) === -1) {
you need to use 2 loop. the first to create datasets and the second to push data :
$('.project').each(function(index, value) {
catName = $(this).data("prefix");
if(!$.contains(datasets,catName)){
datasets[catName] = {
label : catName,
data: []
};
}
});
$('.project').each(function(index, value) {
catName = $(this).data("prefix");
datasets[catName].data.push($(this).val());
});
console.log(datasets);
https://jsfiddle.net/y6c5gw7o/
I'm using vuejs for this project, but this problem is not necessarily connected - but if there is a vue-way, I would prefer that.
I'm building a table, that enables the user to have per-column-filters (in this case simple inputs). The columns are dynamic, so is the amount of data (thousands of rows, but less than 100.000 entries).
// example data
var columns = ['id', 'title', 'date', 'colour']
var data = [{ id: 1, title: 'Testentry 1', date: '2017-02-21T07:10:55.124Z', colour: 'green'}]
Here is the problem: I'm iterating over the columns, checking if a search-input exists, and if so, I try to filter the data based on the searchquery. In case of the ID, the time complexity is O(n). If I know search for a title additionally, I can reuse the result of the first searchquery, dramatically reducing the amount of data has to be looked at.
The searchqueries are stored in an object search, and the filtered data is a computed property, that gets updated whenever search changes. The way how that works though is, that if I change the searchquery for title, it would re-evaluate the searchquery even for the ID, although the searchquery for that didn't change.
This would require some kind of caching of data filtered for each column. And only the proceeding columns need to be queried upon.
edit: added code for the filtering:
filteredRows () {
var rows = this.data
for (var i = 0; i < this.columns.length; i++) {
var column = this.columns[i].name
var search = this.tSearch[column]
if (!search && search.length === 0) continue
console.log(column + ': ' + ' (' + search + ') -> ' + rows.length)
rows = _.filter(rows, (row) => {
var value = '' + row[column]
value.search(search) > -1
})
}
return rows
}
Just a suggestion, but did you try to use a watcher to get old and new value of input.
data: function() {
return {
propertyToWatch: 'something'
}
},
computed: {
...
},
watch: {
'propertyToWatch': function (val, oldVal) {
console.log(oldVal); // logs old value
console.log(val); // logs current value
// here you can call a function and send both of these args and detect diff
}
},
....
In my app I've got 2 functions to work with localStorage.
When I add the first and second items, it works properly, but when it is the third item, it gives an error.
Here are the functions:
w.getLocalStorage = function() {
var c = localStorage.getItem('cities');
var arr = [];
arr.push(c);
return c ? arr : [];
}
w.setLocalStorage = function(data, googleData, cities, name) {
if (data) {
city.name = data.name;
city.coord.lat = data.coord.lat;
city.coord.lon = data.coord.lon;
cities.push(JSON.stringify(city));
// console.log(city);
localStorage.setItem("cities", cities);
} else if (googleData) {
city.name = name;
city.coord.lat = googleData.results[0].geometry.location.lat;
city.coord.lon = googleData.results[0].geometry.location.lng;
console.log('cities', cities);
cities.push(JSON.stringify(city));
// console.log(cities, city);
localStorage.setItem("cities", cities);
}
}
Here is what it returns for the first 2 items:
Array[1]
0 : "{"name":"Pushcha-Voditsa","coord":{"lat":50.45,"lon":30.5}}"
1 : "{"name":"Kyiv","coord":{"lat":50.4501,"lon":30.5234}}"
Here is what when the third items is added:
Array[1]
0 : "{"name":"Pushcha-Voditsa","coord":{"lat":50.45,"lon":30.5}}, {"name":"Kyiv","coord":{"lat":50.4501,"lon":30.5234}}"
1 : "{"name":"Kyiv","coord":{"lat":50.4501,"lon":30.5234}}"
How can I fix this?
As you can only store string in localStorage, to persist object convert them in stringified format using JSON.stringify() method and on retrieval use JSON.parse() to parses the JSON string to construct the JavaScript value or object.
Here are the code snippet, which require attention. You should persist stringified cities data
cities.push(city);
localStorage.setItem("cities", JSON.stringify(cities));
While retrieval, parse it JavaScript object
var cities = localStorage.getItem('cities');
var c = cities ? JSON.parse(cities) || [];
My Json is like this:
[
{"isoCode":"BW","name":"Botswana ","CashOut":"Y","BankOut":"","MMT":null},
{"isoCode":"BR","name":"Brazil ","CashOut":"Y","BankOut":"Y","MMT":null},
{"isoCode":"BG","name":"Bulgaria ","CashOut":"Y","BankOut":"Y","MMT":"Y"},
{"isoCode":"BF","name":"Burkina Faso","CashOut":"Y","BankOut":"","MMT":null},
{"isoCode":"BI","name":"Burundi","CashOut":"","BankOut":"","MMT":"Y"},
{"isoCode":"KH","name":"Cambodia","CashOut":"Y","BankOut":"","MMT":null}
]
I want all the names which have BankOut value as "Y" into an array using JavaScript, in order to use those names in my protractor automation.
You need to use filter method of array. It takes function as it argument. And runs it against each element of array. If function returns true (or other truthy value) then that element stays in newly created array.
var list =[ {"isoCode":"BW","name":"Botswana ","CashOut":"Y","BankOut":"","MMT":null},
{"isoCode":"BR","name":"Brazil ","CashOut":"Y","BankOut":"Y","MMT":null},
{"isoCode":"BG","name":"Bulgaria ","CashOut":"Y","BankOut":"Y","MMT":"Y"},
{"isoCode":"BF","name":"Burkina Faso ", "CashOut":"Y","BankOut":"","MMT":null},
{"isoCode":"BI","name":"Burundi","CashOut":"","BankOut":"","MMT":"Y"},
{"isoCode":"KH","name":"Cambodia","CashOut":"Y","BankOut":"","MMT":null}
];
var onlyBankOutY = list.filter(function (item) {
return item.BankOut === 'Y';
});
document.body.innerHTML = onlyBankOutY.map(function (item) {
return JSON.stringify(item);
}).join('<br>');
var list =[
{"isoCode":"BW","name":"Botswana ","CashOut":"Y","BankOut":"","MMT":null},
{"isoCode":"BR","name":"Brazil ","CashOut":"Y","BankOut":"Y","MMT":null},
{"isoCode":"BG","name":"Bulgaria ","CashOut":"Y","BankOut":"Y","MMT":"Y"},
{"isoCode":"BF","name":"Burkina Faso ", "CashOut":"Y","BankOut":"","MMT":null}, {"isoCode":"BI","name":"Burundi","CashOut":"","BankOut":"","MMT":"Y"},
{"isoCode":"KH","name":"Cambodia","CashOut":"Y","BankOut":"","MMT":null}
];
var names = [];
list.forEach(function(el) {
if (el.BankOut === 'Y') {
names.push(el.name)
}
})
I am attempting to replace the values in an array with the correct case sensitivity. This is because I am attempting to correct user inputs. I retrieve the correct casing from a page, and the user will have an array of values, some of which will be incorrect.
Ex:
userValues = ["apple321", "orange_22", "pineApple" , "Cantelope", "grASShopper_9000"];
var value1 = "Apple321";
var value2 = "orange_22";
var value3 = "Cantelope";
var value4 = "GrassHopper_9000";
Then after some function ran through all the values, the result would be:
userValues = ["Apple321", "orange_22", "pineApple" , "Cantelope", "GrassHopper_9000"];
The reason I have value1, value2, etc is because I've already created a loop to run through an object. Just not sure how to compare the resulting values. Here is what I have already however:
// When the user enters data, it's sometimes case insensitive. This normalizes the data.
function NormalizeData(downloaded_data)
{
$.each(downloaded_data, function(website,streams){
$.each(streams, function(stream_name,value){
stream_list[website] // This is the global variable array
value.displayName; // This is the value I need to check case sensitivity, and replace with the new case if different
});
});
}
Here is the requested data structure:
downloaded_data = {
twitch_tv : {
timthetatman : {
Online: "1",
Website: "twitch_tv",
displayName: "TimTheTatman"
}
}
}
streamlist = {
twitch_tv : {
["timthetatman"]
}
hitbox_tv: {
[]
}
}
I figured it out. Since I am using an array for the values I want to change, and not an object, it's actually much simpler than I thought. I ran a loop on every value, and if the lowercase of both values matched, but the non-lowercase values didn't, I replaced it in the array, using the numerical key as a reference.
function NormalizeData(downloaded_data)
{
$.each(downloaded_data, function(website,streams){
$.each(streams, function(stream_name,value){
$.each(stream_list[website], function(arrKey,arrVal){
if(arrVal.toLowerCase() == stream_name.toLowerCase() && stream_list[website][arrKey] !== value.displayName)
stream_list[website][arrKey] = value.displayName;
});
});
});
}
Here it is, simplified, if the array is called Array1 and the value Value1:
var Array1 = ["apple"];
var Value1 = ["Apple"];
$.each(Array1, function(arrKey,arrVal){
if(arrVal.toLowerCase() == Value1.toLowerCase() && arrVal !== Value1)
Array1[arrKey] = Value1;
});