Adding an array to a Javascript object - javascript

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

Related

jQuery move value to last position

I have the object as,
var names =["LET_ABC","PET_DEF","Num_123","Num_456","SET_GHI","RET_JKL"];
Now i have to move the value which contains "Num" to the last which means after the "Num" value there should be no values.
This is how i add the value to the array,
result.each(function () {
var tempObject = {},
attributes = $(this).data();
names.push(attributes.prefix+ '_' + attributes.value)
});
Can i somehow manipulate the above code to make the "Num" values move at last.
I need something like,
var names =["LET_ABC","PET_DEF","SET_GHI","RET_JKL","Num_123","Num_456"];
for(var i=0;i<names.length;i++){
if(names[i].match("^Num")){
names.push(names.splice(i, 1)[0]);
}
}
Working example (with explanation in comments):-
var names =["LET_ABC","LET_DEF","Num_123","Num_456","LET_GHI","LET_JKL"];//your array
function movetoLast(names,checkword){// function with array and checking prefix
$(names).each(function(index,value){ // iterate over array
if(value.indexOf(checkword) >= 0){ // check value have that prefix or not in it
names.push(names.splice(names.indexOf(value), 1)[0]); // if yes move that value to last in array
}
});
return names; // return modified array
}
var names = movetoLast(names,"Num");// call function
console.log(names); // print modified array in console
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Try this.simple use Array#filter and Array#concat
var names = ["LET_ABC", "PET_DEF", "Num_123", "Num_456", "SET_GHI", "RET_JKL"];
console.log(names.filter(a => !a.match(/(\d+)/g)).concat(names.filter(a => a.match(/(\d+)/g))))
I would put the numbers in a separate array to concatenate the two arrays at the end.
result.each(function () {
var tempObject = {}, attributes = $(this).data();
var numsArray = [];
if (attributes.prefix==Num){
numsArray.push(attributes.prefix+ '_' + attributes.value);
}else{
names.push(attributes.prefix+ '_' + attributes.value)
}
names.concat(numsArray);
});
Use push to add a value to the end of an array if it has the "Num" prefix and use unshift to add a value to the beginning of an array if it does not have the "Num" prefix. Working code:
var names =["LET_ABC","PET_DEF","Num_123","Num_456","SET_GHI","RET_JKL"];
$(document).ready(function(){
result_array = [];
$.each(names, function(index, value){
if (value.substring(0,3)=="Num"){
result_array.push(value);
} else{
result_array.unshift(value);
};
});
console.log(result_array);
});

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

Getting undefined in dropdown from json content

EDIT 2
Check the fiddle - http://jsfiddle.net/SN5zT/2/
Following is the fiddle for which I am not sure why I am getting undefined in dropdown.
My fiddle - http://jsfiddle.net/z6GDj/
var res = '{"allSportPosition":{"25":"Forwards (Strickers)","27":"Fullbacks (Defenders)","28":"Goalkeeper ","26":"Midfielders"}}';
try {
var sportPositionOptions = '';
var parsedJson = JSON.parse(res);
var allSportPosition = parsedJson.allSportPosition;
var values = new Array();
$.each(allSportPosition, function (index, value) {
values[index] = value;
});
//alert(values.length);
values.sort();
$.each(values, function (atIndex, atValue) {
sportPositionOptions = sportPositionOptions + '<option value="' + atIndex + '">' + atValue + '</option>';
});
$(sportPositionOptions).appendTo("#player");
} catch (e) {
alert("Parsing error:" + e);
}
$.each is automatically sorting keys to 25,26,27,28 for res.
Please explain the reason of this and why I am getting undefined ?
Let me know If i need to explain it more, I will surely do it :)
EDIT
Please explain the reason why it is getting sorted automatically http://jsfiddle.net/SN5zT/
Try
values.push(value);
instead of
values[index] = value;
Fiddle Link
The following script is working, I also figured out where the "undefineds" came from.
http://jsfiddle.net/z6GDj/3/
var res = '{"allSportPosition":{"25":"Forwards (Strickers)","27":"Fullbacks (Defenders)","28":"Goalkeeper ","26":"Midfielders"}}';
try{
var sportPositionOptions = '';
var parsedJson = JSON.parse(res);
var allSportPosition = parsedJson.allSportPosition;
var values = allSportPosition;
//$.each(allSportPosition, function(index, value) {
// values[index] = value;
//});
//alert(values.length);
$.each(values,function(atIndex, atValue){
sportPositionOptions = sportPositionOptions+'<option value="'+atIndex+'">'+atValue+'</option>';
});
$(sportPositionOptions).appendTo("#player");
}
catch(e){
alert("Parsing error:"+ e);
}
The array is sorted automatically, because the keys are set correctly.
see http://www.w3schools.com/js/js_obj_array.asp. "An array can hold
many values under a single name, and you can access the values by
referring to an index number."
Or: Change the index, and you´re changing the order. (index indicates the order).
The undefined values are created by javascript default, check the last answer in here (How to append something to an array?)
"Also note that you don't have to add in order and you can actually
skip values, as in
myArray[myArray.length + 1000] = someValue;
In which case the values in between will have a value of undefined."
Since you are passing an object to each(), jquery passes the key as the index parameter. In your object, the keys are ranged from 25 to 28. Setting the array using the values[25] on an empty array will expand the array to index 25, with the first 25 elements undefined. Using values.push(value) will append the value at the end of the array.
$.each is doing the following assignment that is why you are getting so many undefined
values[25] = "Forwards (Strickers)"
values[26] = "Midfielders"
values[27] = "Fullbacks (Defenders)"
values[28] = "Goalkeeper"
During $.each browsers will automatically sort the keys if the keys are integer, one way to avoid this is use non integer keys
What you need to do is define your options before you sort them , and then append them to your select:
var res = '{"allSportPosition":{"25":"Forwards (Strickers)","27":"Fullbacks (Defenders)","28":"Goalkeeper ","26":"Midfielders"}}';
try {
var sportPositionOptions = '',
parsedJson = JSON.parse(res),
allSportPosition = parsedJson.allSportPosition,
options = new Array();
$.each(allSportPosition, function (index, value) {
options[index] = $('<option></option>', {
value: index,
text: value
});
});
$.each(options, function (index) {
$('#player').append(options[index]);
});
} catch (e) {
alert("Parsing error:" + e);
}
jsfiddle: http://jsfiddle.net/z6GDj/11/

How to push onto a multidimensional associative array

I'm looping through some HTML form elements on a page like so.
var itemsArray = new Array();
$('input[type="text"].qty').each(function(index) {
if($(this).val()) {
itemsArray[index]['qty'] = $(this).val();
itemsArray[index]['itemPrice'] = $(this).parents('.control-group').find('.itemPrice').val();
itemsArray[index]['itemID'] = $(this).parents('.control-group').find('.itemID').val();
}
});
The index i'm hoping to be 0,1,2,3 etc.. like a regular array. With the sub elements being associative and assigned to various values.
I'm getting this error in the console.
TypeError: itemsArray[index] is undefined
You need to make sure each item in the outer array is initialized before you start using it. Note, I changed to object notation below just for clarity.
$('input[type="text"].qty').each(function(index) {
if($(this).val()) {
itemsArray[index] = {};
itemsArray[index].qty = $(this).val();
itemsArray[index].itemPrice = $(this).parents('.control-group').find('.itemPrice').val();
itemsArray[index].itemID = $(this).parents('.control-group').find('.itemID').val();
}
});
Consider using an array of objects. Arrays in Javascript are not really intended to be used in the way you are (the multidimensional part). Also itemsArray = [] is preferred over new Array().
var itemsArray = [];
$('input[type="text"].qty').each(function(index) {
if($(this).val()) {
itemsArray.push({
qty : $(this).val(),
itemPrice : $(this).parents('.control-group').find('.itemPrice').val(),
itemID : $(this).parents('.control-group').find('.itemID').val()
});
}
});
It means what it says. itemsArray[index] is undefined, and you cannot assign properties on this. Notice that you don't have a "multidimensional array", but just an array of objects. For each new index, you will need to create a new object.
var $this = $(this);
if ($this.val()) {
var $parent = $(this).parents('.control-group'); // .closest() should suffice
itemsArray[index] = {
qty: $this.val(),
itemPrice: $parent.find('.itemPrice').val(),
itemID: $parent.find('.itemID').val()
};
}

jquery split() issue

Hopefully this is easy for someone.
I have a set of checkboxes with values 1,2,3 etc with the same name attribute (cp_bundle).
I use the following code to get a comma-delimited list of those checkboxes.
var hl_calling_plan_bundle = $('input[name="cp_bundle"]:checked').getCheckboxVal() || "";
jQuery.fn.getCheckboxVal = function(){
var vals = [];
var i = 0;
this.each(function(){
vals[i++] = jQuery(this).val();
});
return vals;
}
if I check the first and third checkboxes, the following will be returned:
1,3
Then, I want to run a test to see whether a particular value (e.g. "3") exists in the the returned variable
But, I can't get past the split of the variable using the following:
var aCallingBundle = hl_calling_plan_bundle.split(",");
This gives the error:
hl_calling_plan_bundle.split is not a function
Any idea what's going on?
hl_calling_plan_bundle is an array. You have to use array operations on it, not string operations.
If you want to know if the value 3 is in the array, then you have to search the array for it. There are many ways to search an array, but since you have jQuery, it's easy to use the .inArray() function:
var index = $.inArray(3, hl_calling_plan_bundle);
if (index != 1) {
// found 3 in the array at index
}
Incidentally, you may want to simplify your function like this:
jQuery.fn.getCheckboxVal = function(){
var vals = [];
this.each(function(){
vals.push(this.value);
});
return vals;
}
or this way:
jQuery.fn.getCheckboxVal = function(){
return(this.map(function(){return(this.value)}).get());
}
split() is a String method, it does not exist on an Array.
When you say the following is returned 1,3, you may be implicitly calling the String's toString() method, which will by default join() the array members with a comma. If you explicitly called toString(), then you could call split(), but that would be an anti pattern.
You don't need to split the string, you can just use RegEx to search:
var str = '1,3,22,5';
/\b1\b/.test(str); // true
/\b2\b/.test(str); // false
/\b3\b/.test(str); // true
/\b5\b/.test(str); // true
/\b22\b/.test(str); // true
Making it a function:
String.prototype.findVal = function(val){
var re = new RegExp('\\b' + val + '\\b');
re.lastIndex = 0;
return re.test(this);
};
str.findVal(2); // false
str.findVal(22); // true
To get the checkboxes:
var cbs = document.getElementsByName('cp_bundle');
To get arrays of all values and the checked values:
var allValues = [];
var checkedValues = [];
for (var i=0, iLen=cbs.length; i<iLen; i++) {
if (cbs[i].checked) checkedValues.push(cbs[i].value);
allValues[i] = cbs[i].value;
}

Categories