jQuery object array from input - javascript

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/

Related

How to access object with a randomly chosen name stored in a variable?

I've got 16 objects with names like: aBoard, bBoard, cBoard and so on,
eg. let aBoard = { currentValue: 0, valuesHistory: [], ID: "unitA", borderValues: [1, 0, 0, 1], free: true };
I have an array of corresponding names, randomly chose one of them and change it so it matches the name of one of the objects.
const BOARDARRAY = ["unitA", "unitB", "unitC", "unitD", "unitE", "unitF", "unitG", "unitH", "unitI", "unitJ", "unitK", "unitL", "unitM", "unitN", "unitO", "unitP"];
let randomizer = Math.floor(Math.random()*16);
currentBoardTile = BOARDARRAY[randomizer];
let temp = (currentBoardTile.charAt(currentBoardTile.length -1).toLowerCase());
JSObjectBoardUnit = (temp + "Board");
How to access the object using my JSObjectBoardUnit?
In other words, how to make JS "understand" that I want to treat JSObjectBoardUnit value (string) as a value of the object address?
Eg. Let's day JSObjectBoardUnit = aBoard;
Basically the outcome I want is: aBoard.key1 = JSObjectBoardUnit.key1.
I'd love to use the value stored in JSObjectBoardUnit to access the name of the predefined object aBoard.
I'm not sure to understand well your question but I think this 2 methode could maybe help you.
You can access attribute of a object with a string by using
const obj = {toto: 1};
const name = "toto";
console.log(obj["toto"]); // 1
console.log(obj[name]); // here we use variable and the result is 1
so you could store all yoyr object inside one and do this.
const allBoard = {
"aboard": null, // do not put null use your board
}
console.log(allBoard[(temp + "board")]); // display the temp + board attribute so if temps is equal to a then it will get the aboard
this is what you want, getting object from a string.
But I saw that the aboard also have an id attribute with "unitA"
Instead you could build an array of aboard, bboard ....
and use the Array.find() methode that will return the object that match the condition.
in your case
const myBoardArray = [{ currentValue: 0, valuesHistory: [], ID: "unitA", borderValues: [1, 0, 0, 1], free: true }, ....];
let randomizer = Math.floor(Math.random()*16);
currentBoardTile = BOARDARRAY[randomizer];
myBoardArray.find((board) => board.ID === currentBoardTile);
2 options
Put the boards in a list, and iterate over them with a for loop. In the for loop, use an if statement to see which Id matches the board you want.
let boards = [aBoard , bBoard, cBoard];
boards.forEach(board=> {
if (board.ID == currentBoardTile) {
//do something
}
});
Create a dictionary where the key is the board id and the respective object is the value. Use the board id to get the respective value.
var boards = {
"unitA" : boardA,
"unitB" : boardB,
....
};
currentBoardTile = BOARDARRAY[randomizer];
console.log(currentBoardTile + " : " + boards[currentBoardTile]);

angularjs dynamic label name for array inside array push

I am creating array using below format,
angular.forEach(value.data, function(value1, key1) {
shiftArrayList.push({
shift: value1.shiftName
});
dataArrayList.push({
safeDayCount: value1.safeDayCount,
accidentCount: value1.accidentCount,
hazardCount: value1.hazardCount,
nearMissCount: value1.nearMissCount
});
});
and the result for dataArrayList will be like,
"safeDayCount": 0,
"accidentCount": 0,
"hazardCount": 39,
"nearMissCount": 0
and it continues. But i need to append the label name inside the foreach and for every label i need to append value1.shiftName. like safeDayCount + "_"+value1.shiftName. So it will be like safeDayCount_X, accidentCount_X, hazardCount_X, nearMissCount_X.. Please help me to append the value.
Thanks in Advance,
You need to prepare the object like this
var props = [ "safeDayCount", "accidentCount", "hazardCount", "nearMissCount" ];
var obj = {};
props.forEach( function(item){
obj[ item + "_" + value1.shiftName ] = value1[ item ];
});
dataArrayList.push( obj );

How to get JSON Data depending on other data values in JavaScript

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)
}
})

Create or Update cookie array in Jquery

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();

Check case insentively if a value is in an array, and if the case doesn't match, replace it with the new value

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;
});

Categories

Resources