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()
};
}
Related
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;
})
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()
});
}
});
I have the below code:
var changes = new Array();
$(".item_prices").on("blur", function(){
var item_id = $(this).attr("id");
var item_price = $(this).html();
changes[item_id] = item_price;
});
Every time a new value is entered, I want to save the item's ID as the key and its price as the value. If I save items with IDs 4 and 6 and prices 1.99 and 2.99, respectively, I get the following array:
{,,,,1.99,,2.99}
How do I add to the array without incurring empty values?
Use object, not Array:
var changes = {};
The rest is the same.
Key-value should always be saved in an object.
Since you're using jQuery, here is another answer to an unasked question,
Use native javascript functions when it's possible and simple, specially when it's even simpler:
var item_id = $(this).attr("id");
var item_price = $(this).html();
Can and should be:
var item_id = this.id
var item_price = this.innerHTML;
You don't want an array, a simple object will form a collection of key value pairs for you:
var changes = {};
If / when the time comes to enumerate these changes:
for (var name in changes) {
if (changes.hasOwnProperty(name)) {
var value = changes[name];
...
}
}
Arrays are a special case of objects, whose elements have consecutive integer keys. You don't have consecutive keys, so Array is "filling the gaps" for you.
Use a barebones Object instead:
var changes = {};
It seems complicated for me.
First, I have this list:
liste_path_categories.push(
{ index: null
, letter: "letter1"
, type: key
, picture_url: "url1"
, id_categ: null
, response: "Answer here"
});
What I want is to extract from this big list an object in this form:
data["String1"]["String2"]= String3
With :
String1=list_path_categories[i].letter
String2=list_path_categories[i].id_categ
String3=list_path_categories[i].response
example:
data['A']['12'] : "A_answer"
To declare the data i make this:
var data = new Object(new Object);
How I can set all the values in data?
You can use the Array.forEach method to iterate through liste_path_categories and construct your data object.
Example:
var liste_path_categories = [];
var data = {};
liste_path_categories.push(...);
...
liste_path_categories.push(...);
liste_path_categories.forEach(function(element) {
data[element.letter] = {};
data[element.letter][element.id_categ] = element.response;
});
jsFiddle example : http://jsfiddle.net/3ZvNf/
Your question is pretty vague but do you mean something like this?
Setting a dynamic property in an object wich belongs to another object?
data['A']['12'].answer = "A_answer"
Instead of using strings, you have to use the variables in your property access:
var data = {};
if (!data[String1]) {
data[String1] = {}; // make sure that data[String1] exists and is an object
}
data[String1][String2] = String3;
If you want to do this for elements in the array, you have to iterate over the array.
P.S.: I recommend to use more expressive variable names than StringX.
first create the constructor (in OOP terminology):
var ctor_object = function(letter,id_categ,response)
{
this.letter = letter;
this.id_cated = id_categ;
this.response = response;
}
(in genereal you should omit the ctor_ syntax and name it directly after the name of the class of your object)
then use your constructor upon your list of categories:
var length = liste_path_categories.length,
element = null;
for (var i = 0; i < length; i++)
{
element = liste_path_categories[i];
my_obj = new ctor_object(element.letter,element.id_categ,element.reponse)
// Do something with my_obj
}
How can you create an array with from a set of elements with same rel?
Eg:
<a rel='array' id='2' url='aa'></a>
<a rel='array' id='5' url='bb'></a>
<a rel='array' id='8' url='cc'></a>
Array:
[2] > aa
[5] > bb
[8] > cc
I put each URL as value just to use something. But having the IDs ordered should be enough.
How can this be done?
const anchors = document.getElementsByTagName('a'), arr = [];
for (let i = 0; i < anchors.length; i++){
let current = anchors[i];
if(current.getAttribute('rel') == 'array') {
// arr.push(current.getAttribute('url'));
arr.push({ 'id' : current.id, 'url' : current.getAttribute('url') });
}
}
http://jsfiddle.net/8ScSH/
Or, more succinctly:
const anchors = [...document.getElementsByTagName('a')];
const arrs = anchors.filter(x => x.getAttribute('rel') === 'array')
.map(x => { return { 'id': x.id, 'url': x.getAttribute('url') } });
Not enough jquery!
var arr = [];
$('a[rel="array"]').each(function(){
arr.push($(this).attr('url'));
});
Very easy if you're using jquery:
var arr = [];
$('a[rel="array"]').each(function() {
arr.push($(this).attr('url'));
});
Fiddle
var itemArray = [];
$("a[rel='array']").each(function() { itemArray.push($(this).attr("url") });
Try
var a = {};
$('#wrap a').each(function() {
if($(this).attr('rel') === "array") {
a[$(this).attr('id')] = $(this).attr('url');
}
});
An array won't cut it, you need an object. Here live: http://jsfiddle.net/martincanaval/rAPkL/
var elements = [];
$('a[rel="array"]').each(function() {
elements[this.id] = $(this).attr('url');
});
Note that this creates a sparse array with only the index values specified by the element ids, which doesn't make much sense to me, but that's what you asked for. It really doesn't make sense if any of the ids can be non-numeric - if so you should use an object rather than an array, i.e.:
var elements = {};
"I put each URL as value just to use something. But having the IDs ordered should be enough."
If your intention is to get an array of the ids then you can do this:
var elementIds = [];
$('a[rel="array"]').each(function() {
elementIds.push(this.id);
});
That would create the array ['2', '5', '8'] where the ids will be in the order that they appear within your source html.
However, just saying $('a[rel="array"]') gives you a jQuery object that is an array-like structure holding all the matching elements - that's why we can iterate over each of the elements using the .each() method. So it's possible that whatever you're really trying to do can be done directly with jQuery rather than setting up your own array.