javascript dynamically add values to array - javascript

I'm trying to loop over the checkboxes in a form and add their values to a multidimensional javascript object. The 'attrib' data attribute will be the key. Possible key values are 'category', 'product_group' and 'language' but I'd rather add them dynamically in case any more get added in the future.
I want to end up with an object like this, which I can easily send as a json_encode 'd single value to the server.
values = {
'category' : {1,2,3},
'product_group' : {4,5,6},
'language': {'en','fr','de'}
};
Code below. Here obviously each iteration overwrites existing values instead of adding to it. I'm unsure where I can create values[key] as an object ... ?
$('.filter input, .multiselect-container input').change(function() {
var values = {}
$('.filter input:checked').each(function() {
if($(this).is(':checked')) {
var key = $(this).data('attrib')
var value = $(this).val()
values[key] = value
// values[key].push(value) = calling method push of undefined ...
}
else {
// Remove value
}
})
console.log(values)
})

Your error is due to the fact that values[key] is undefined, therefore does not have a push method.
Try this code:
if($(this).is(':checked')) {
var key = $(this).data('attrib')
var value = $(this).val()
values[key] = values[key] || [] // initialize with empty array
values[key].push(value)
}

Not sure that's what you are looking for:
if(!values[key])
values[key]=new Array();
values[key].push(value);
But this way you can add an array of value to every key.

Try this:
if($(this).is(':checked')) {
var key = $(this).data('attrib')
var value = $(this).val()
if(typeof values[key] == "undefined")
values[key] = [];
values[key].push(value);
}
else {
// Remove value
}

First, your data representation is not correct. The object attributes should be arrays like this:
values = {
'category' : [1,2,3],
'product_group' : [4,5,6],
'language': ['en','fr','de']
};
With that data representation, this piece of code will do what you want:
$('.filter input, .multiselect-container input').change(function() {
var values = {}
$('.filter input:checked').each(function() {
if($(this).is(':checked')) {
var key = $(this).data('attrib')
var value = $(this).val()
values[key] = value
if (values.key == undefined){
//Check if key exists. If not, create it as an array
values[key] = Array()
values[key].push(value)
}
else{
values[key].push(value)
}
}
else {
// Remove value
}
})
console.log(values)
})

Related

Remove already exist object from array otherwise insert

Below javascript code for adding object to a javascript array. I want to add an object to array when it does not exist, if it already exists object.rValue!= new object.rValue then change old rValue=new rValue, otherwise same rVale. Also save it on array.
The problem is the object populate dynamically.
var arr = [];
$(document).ready(function() {
$(".rating").click(function() {
var idx = $(this).closest('td').index();
var userskill = {
tech : $(this).closest('td').siblings('td.tech').text(),
skill : $('#listTable thead th').eq(idx).text(),
rValue : $(this).val()
}
validate(userskill);
});
});
function validate(userskill) {
}
Try this
arr.forEach(function(elem){
if(elem.rValue==newObj.rValue)
elem.rValue = newObj.rValue;
})

Adding an array to a Javascript object

I have some code I want to put into a JSON object ultimately. But first I want to create a javascript object and within that object add an array of values. Sounds simple enough but my approach seems wrong. First I create a basic object, the set a few fields. Lastly, iterate over a bunch of checkboxes and then, if one is checked at that value to an array.
At the last step I need to add that array to my object (myData) and then JSONify it.
Any ideas how I can do this, seems myData.push(filters); doesn't work...
Note that the object itself is not an array, I want to place an array IN the object.
var myData = new Object();
myData.deviceId = equipId;
myData.dateTo = dateTo
myData.dateFrom = dateFrom;
myData.numResults = $("#numResults").val();
var i=0;
var filters = [];
$('input[type=checkbox]').each(function () {
if (this.checked) {
allData += $(this).val() + ",";
filters[i] = {
filterIds: $(this).val()
};
++i;
}
});
myData.push(filters);
That's not how to add items to an Object, change
myData.push(filters);
to
myData.filters = filters;
Also, maybe change = new Object to = {}. There's no difference, but it's easier to read, because literal notation takes up less space.
Read more about Array.prototype.push
Use push to add elements to the filters array. Use property assignment to add another property to the myData object.
var myData = {
deviceId: equipId,
dateTo: dateTo,
dateFrom: dateFrom,
numResults: $("#numResults").val()
};
var filters = [];
$('input[type=checkbox]').each(function () {
if (this.checked) {
allData += $(this).val() + ",";
filters.push({
filterIds: $(this).val()
});
}
});
myData.filters = filters;
BTW, don't use new Object() to create an object, use {}.
Remove the need for an extra array and i.
var myData = {}
myData.deviceId = equipId;
myData.dateTo = dateTo
myData.dateFrom = dateFrom;
myData.numResults = $("#numResults").val();
myData.filters = [];
$('input[type=checkbox]').each(function () {
if (this.checked) {
allData += $(this).val() + ",";
myData.filters.push({
filterIds: $(this).val()
});
}
});

jQuery $.inArray() always return -1 with an array of object

I have an array of object, that contain key value pair of columnNames.
when i check if a particular columnName exists it alwayz returns -1
Here is an sample http://jsfiddle.net/trLkt/6/, Help will b appriciated
You're searching for string values in the columnModel array, but you're storing objects in it (columnModel.push({'colName': $(this).text()});). $.inArray() cannot decide by itself to compare against the colName property of each array element, it simply compares the value you're searching for against each array element.
Two things you can do:
Add strings to the array instead of objects using .push (as suggested by #lanzz), then $.inArray will work as you expect.
Alternatively, if you do need to store objects within the array (if for example you need to have multiple properties within each object) you would need to iterate over each object and see if the colName already exists:
var colExists = false;
var text = $(this).text();
$.each(columnModel, function(k, v) {
if(text == v['colName']) {
colExists = true;
}
});
Then change your check from if(colExists === -1) to if(!colExists).
Example
$(function () {
$('#ddlMain').change(function (event) {
$('option:selected', $(this)).each(function () {
var colExists = false;
var text = $(this).text();
$.each(columnModel, function(k, v) {
if(text == v['colName']) {
colExists = true;
}
});
if(!colExists) {
columnModel.push({'colName': $(this).text()});
alert($(this).text() + ' added to columnModel');
}
});
});
});

Assigning Unordered keys to a Js array

I am getting a random key value pair,Can i assign it to an array?
Its problematic here when I assign it like arr[50] = 'abc' it automatically creates the keys upto 50 like arr[0],arr[1],arr[2] and so on.
and i wanted an array like this arr[50=>'abc','40'=>'pqr','53'=>'lmn']
I have it here
if(typeof(feedArr.latestRating) == 'object'){
jQuery.each(feedArr.latestRating,function(key,val){alert('key::'+key);
if(key in newRatingArr){
//delete the key if already exists
newRatingArr.splice(key,1);
}else{
//insert the key,value
newRatingArr[key] = val; //here is the problem occurs when key is 50 it automatically creates the indexes in the array upto 50 which i dont want
// alert('Key between::'+key);
// alert('Value between::'+newRatingArr[key]);
//newRatingArr.splice(key,0,val);
}
//alert(key);
emptyRate = 0;
});
}else{
emptyRate = 1;
}
What can i do here?Please let me know.
Use an object {} instead of an array [].
Objects can act as unordered key-value containers, which is what you seem to be needing here.
// somewhere...
var newRatingArr = {};
// your code.
var emptyRate = true;
if (typeof (feedArr.latestRating) == 'object') {
jQuery.each(feedArr.latestRating, function (key, val) {
newRatingArr[key] = val;
emptyRate = false;
});
}

Dereferencing a variable to its value to use in another function javascript

function get_event_ids_from_dom()
{
var event_ids = {};
$.each(
$("td.ms-cal-defaultbgcolor a"),
function(index,value){
var str = new String(value);
var id = str.substring(str.indexOf('=')+1,str.length);
if(typeof(event_ids[id]) == "undefined")
{
event_ids[id] = this;
}
else
{
**event_ids.id.push(this);**
}
}
)
return event_ids;
}
In above javascript event_ids is a hashtable. I am trying to assign values to this hashtable.
A hashtable can be added with multiple values using "hashtable.key.push(value)". I am trying to do this using event_ids.id.push(this); in the above code.
I have declared "id" as a variable in the code. The problem is, I am not able to dereference variable "id" to its value.
Is this possible in jquery/javascript?
Example use of hashtable:
event_ids = {};
event_ids["1"]= 'John';
event_ids.1.push('Julie');
The above example would add john and julie to hash table.
Try this instead:
function get_event_ids_from_dom() {
var event_ids = {};
$.each(
$("td.ms-cal-defaultbgcolor a"),
function(index,value){
var str = value.toString();
var id = str.substring((str.indexOf('=') + 1), str.length);
if(typeof(event_ids[id]) == "undefined") {
event_ids[id] = [];
}
event_ids[id].push(this);
});
return event_ids;
}
Please, note that while object["id"] is the same as object.id, object[id] is not.
Nicola almost had it:
if(typeof(event_ids[id]) == "undefined") {
event_ids[id] = [];
}
event_ids[id].push(this);
Also please read the comment I left for your question.
In my opinion event_ids is an object (there are no hastables in javascript, just either indexed arrays or objects).
What you are tring to do is using push (an array method) on something that is not an array so i think you must change something:
you could try:
if(typeof(event_ids[id]) == "undefined")
{
event_ids[id] = [];// the property id of object event_ids is an array
event_ids[id].push(this);
}
else
{
event_ids[id].push(this);
}
It should work

Categories