Using a for loop with JSON object/array elements? - javascript

I'm trying to create a for() loop with JSON data that's already been decoded, the problem is adding my loop variable (in this case i), to the end of the element that I'm referencing.
For example, my JSON structure, dumped:
{
"url": "http://www.example.com",
"rid": 1,
"rname": "Apple iPhone 4 Rotation",
"rmin": 90,
"rmax": 150,
"blank": 0,
"geo_country_0": "GB",
"geo_url_0": "http://en",
"geo_country_1": "FR",
"geo_url_1": "http://fr",
"geo_country_2": "ES",
"geo_url_2": "http://es"
}
In the case of geo_country_ and and geo_url_ I need to append a number, in this case the loop variable.
My actual for loop, for a better understanding:
for(i = 1; i < count; i++) {
$('#geo-location').append('<div id="glt_' + i + '" class="clone"><select name="g_country['+i+']" class="glt-input-c">' + options + '</select><input type="text" name="g_url[' + i + ']" class="glt-input-c" value="' + data.geo_url_i+ '"/></div>');
$('select[name="g_country['+i+']"').find('option[value="' + data.geo_country_i+ '"]').attr('selected','selected');
}
So far I've tried:
Encasing the the i like [i].
Escaping it like \i. (This was probably a stupid idea).
Adding a pre-fixing + like, + data.geo_country + i +.
What do I need to do to have i interpreted properly?
Any help would be greatly appreciated!

In JavaScript, you may address an object's properties in two ways:
var value = myobject.myproperty;
var value2 = myobject['myproperty'];
Using this knowledge, you can rewrite your code as follows:
for(i = 1; i < count; i++) {
$('#geo-location').append('<div id="glt_' + i + '" class="clone"><select name="g_country['+i+']" class="glt-input-c">' + options + '</select><input type="text" name="g_url[' + i + ']" class="glt-input-c" value="' + data['geo_url_' + i] + '"/></div>');
$('select[name="g_country['+i+']"').find('option[value="' + data['geo_country_' + i] + '"]').attr('selected','selected');
}

Access it like
data['geo_country_' + i]
And you should have no issues

Related

output is [object,Object] even with JSON.stringify

I have a JSON file with numerous entries. Below is just 2 of them.
{
"layers": [
{
"name": "Test1",
"id": "Feature",
"subject": "General"
},
{
"name": "Test2",
"id": "Feature",
"subject": "General"
}
]
}
When I run this script and all checkboxes are rendered ok. When I click one of them, I get the output at the console as [object,Object]. Can't see any of properties. I tried the JSON.stringify but no success. Ideas? Thanks.
function XX(){
var mydata = JSON.parse(data)
subjects = []
for (var i = 0; i < mydata.layers.length; i++) {
theID = mydata.layers[i].name
subjects[i] = mydata.layers[i].subject
if (!thecontent[subjects[i]]) {
thecontent[subjects[i]] = '<input type="checkbox" id="' + theID + '" onclick=\'window.loadFL("' + mydata.layers[i] + '")\'>'
} else {
thecontent[subjects[i]] += '<input type="checkbox" id="' + theID + '" onclick=\'window.loadFL("' + mydata.layers[i] + '")\'>'
}
thecontent[subjects[i]] += '<label for="' + theID + '"> ' + mydata.layers[i].name +
'</label><br>'
}
for (k = 0; k < subjects.length; k++) {
document.getElementById(subjects[k]).innerHTML = thecontent[subjects[k]] + '<br>'
}
}
}
window.loadFL = function (theresponse) {
console.log(theresponse);
}
When you do this:
thecontent[subjects[i]] += '<input type="checkbox" id="' + theID + '" onclick=\'window.loadFL("' + mydata.layers[i] + '")\'>'
or let me mod it into a simpler form, for ease of discussion:
const myInput = '<input onclick=\'loadFL("' + myObject + '")\'>'
You’re concatenating object to string with + operator. That’ll type-cast object into string type, by implicitly calling myObject.toString() method (inherited from Object.prototype) which will return the string "[object,Object]".
So if you console.log(myInput), you’ll see this:
<input onclick='loadFL("[object, Object]")' >
Above is the explanation.
Below is solution.
If you only need to pass the JSON string value to loadFL. You can do:
const myInput = '<input onclick=\'loadFL(' + JSON.stringify(JSON.stringify(myObject))+ ')\'>'
You read it right, remove the double quotes " in the string, and use JSON.stringify twice.
But if you need to pass the object value, there’s no easy way using HTML string. I’d suggest you use JavaScript to add event listener to HTML node.
If JSON.stringify() doesn't work, you can try to print the index of layers like this:
// some code
thecontent[subjects[i]] = '<input type="checkbox" id="' + theID + '" onclick=\'window.loadFL("' + i + '")\'>'
// some code
window.loadFL = function (layers_index) {
console.log(mydata.layers[layers_index]);
}

create and append multiple elements with data from JSON

Let data be a JSON,
what I am trying here is appending multiple elements according to the data from JSON to the div ,
<div class="studentTab" ></div>. How can I achieve this ?
(nb: please consider that we have 2 Languages and 2 Specializations)
for (i = 0; i < 10; i++) {
var html = '<div class="dtls">' +
'' +
'<h4 class="verified">' + data.student[0].firstName + '</h4 >' +
'<ul>' +
'<li>' + data.student[0].location + '</li>' +
'<li>' + data.student[0].mark + ' /hour</li>' +
'<li>' + data.student[0].year+ ' accademic year</li>' +
if (data.student[0].Languages != null)
{
var lang = string.Join(",", data.student[0].Languages.Select(it => it.Name));
<li>lang </li>
}
if (data.student[0].Specializations.length > 1)
{
var rcount = data.student[0][index].Specializations.length - 1;
<li>data.student[0].Specializations[0].Name + rcount more</li>
}
else
{
<li>data.student[0].Specializations[0].Name</li>
}
'</ul>' +
'</div>'
$('#studentTab').append(html);
};
You may use map() for solving such problem. Please make check:
If your 'data' is underfined or not;
Better save your data.student[0] in some variable;
You never know how many objects inside of data you have. Probably some times is underfined due to network errors or more or less objects due to some back-end updates

Unable to display total using append

I am making a food delivery app. I would like that there would be a place whereby it would display the total. Right now, I am unable to display the total amount from multiplying quantity and price. It does not show up on the app.
And, there are no errors on the console too.
Javascript Code:
function _showorderResult(arr) {
var value1 = arr[0].price;
var value2 = arr[0].quantity;
for (var i = 0; i < arr.length; i++) {
result = value1 * value2;
htmlstring = "";
$("#itemimage").html("<img src='" + serverURL() + "/images/" +
arr[i].imagefile + "' width='200'>");
$("#price").html("Price" + ": " + " $" + arr[i].price);
$("#itemname").html("Item" + ":" + arr[i].itemName);
$("#quantity").html("Quanitiy" + ":" + arr[i].quantity);
$("result").append(htmlstring);
$("#requestedDateTime").html("To delivery by" + ":" + arr[i].requestedDateTime);
$("#deliveredDateTime").html("Delivered on" + ":" + arr[i].deliveredDateTime)
}
}
And, there are no errors on the console too.
There were plenty of errors in my console, but there are several mistakes here. The first is that your code is not runnable. Please consider making a minimal, verifiable example.
Next, you are misusing or not properly formatting the append(...) function. That's intended to append HTML elements, not string values.
As the comments suggest, you seem to have confused var result and $("result"). If you're not using the DOM selector, you probably don't want to jQuery-wrap your variables. The proper jQuery-wrap syntax would have been $(result) without the double quotes, but please don't do that either, it doesn't offer any benefit over just var result. htmlstring doesn't contain any actual HTML, so I've renamed it runningTotal instead and add it to the price * quantity. This must be initialized first or you'll get NaN.
Make sure to initialize your variables. To this point, there's some hard-coded indexes such as value1 = arr[0].price which make no sense in this pasted code. We can assume you left these here after troubleshooting. Please clean them up next time.
Finally, this is minor, but be consistent with your object names... e.g. imagefile versus imageFile. It doesn't matter which you choose so as long as you're consistent. This will help find typos down the road.
Here's a working example:
<html>
<img src="" id="itemimage">
<p id="price">Price: $0.00</p>
<p id="itemname">Item: None</p>
<p id="quantity">Quantity: None</p>
<p id="result">Running: None</p>
<p id="requestedDateTime">To delivery by: None</p>
<p id="deliveredDateTime">Delivered on: None</p>
<script>
var order = [{
price: 5,
quantity: 3,
itemName: 'Pizza',
imagefile: 'pizza.png',
requestedDateTime: '12:00',
deliveredDateTime: '12:30'
}];
/** Dummy function to allow code to run **/
var serverURL = function() { return ""; }
function _showorderResult(arr) {
// var value1 = arr[0].price;
// var value2 = arr[0].quantity;
var result;
var runningTotal = 0;
for (var i = 0; i < arr.length; i++) {
result = arr[i].price * arr[i].quantity;
runningTotal += result;
$("#itemimage").html("<img src='" + serverURL() + "/images/" + arr[i].imagefile + "' width='200'>");
$("#price").html("Price" + ": " + " $" + arr[i].price);
$("#itemname").html("Item" + ":" + arr[i].itemName);
$("#quantity").html("Quanitiy" + ":" + arr[i].quantity);
$("#result").html("Running" + ":" + runningTotal);
$("#requestedDateTime").html("To delivery by" + ":" + arr[i].requestedDateTime);
$("#deliveredDateTime").html("Delivered on" + ":" + arr[i].deliveredDateTime);
}
}
_showorderResult(order);
</script>
</html>

Trouble passing entire two dimensional array as parameters in JavaScript/jQuery

I am trying to generate divs around each of the elements of a two dimensional array using the methods below. So far the code only outputs the last 3 elements in the array (the 3 elements of third nested array). I am passing the array elements as parameters using .apply. How could I modify this to output each element of the array catArray in order? And why would it only pass the last 3 as it is? Any advice would be appreciated, I am trying to understand this better. I have spent hours on this, hopefully someone can help.
Here is a codepen:
http://codepen.io/anon/pen/kzEdK
function cats(catName, catFur, catEyes) {
$("#row").html('<div>' + catName + '</div>' + '<div>' + catFur + '</div>' + '<div>' + catEyes + '</div>');
}
var catArray = [
["fluffy", "soft", "green"],
["mittens", "coarse", "fire"],
["wiskers", "none", "grey"]
];
function catGenerator() {
for (var i = 0; i < catArray.length; i++) {
var blah = catArray[i];
cats.apply(this, blah);
}
}
catGenerator();
You probably want something like:
function cats(catName, catFur, catEyes) {
// note the difference (append() instead of html())
$("#row").append('<div>' + catName + '</div>' + '<div>' + catFur + '</div>' + '<div>' + catEyes + '</div>');
}
function catGenerator() {
$("#row").html(""); // in case you wish to call catGenerator() multiple times, clear the row before appending to it
for (var i = 0; i < catArray.length; i++) {
var blah = catArray[i];
cats.apply(this, blah);
}
}
It shows only the last 3 elements because $("#row").html("...") overwrites the contents of #row three times and the value set in the last iteration remains visible. I fixed that by replacing html() with append(), which does what you want.
The problem is that you have $("#row").html() which will replace the markup within the div tag after each iteration. Consider using $("#row").append()
function cats(catName, catFur, catEyes) {
$("#row").append('<div>' + catName + '</div>' + '<div>' + catFur + '</div>' + '<div>' + catEyes + '</div>');
}
var catArray = [
["fluffy", "soft", "green"],
["mittens", "coarse", "fire"],
["wiskers", "none", "grey"]
];
function catGenerator() {
for (var i = 0; i < catArray.length; i++) {
var blah = catArray[i];
cats.apply(this, blah);
}
}
catGenerator();

Creating an array object within an array object

I have an array object that needs another array object added to it. So i have details of the object that need the rows in a table to be added to that object as an array. I have tried a few suggestions on stackoverflow , but none seems to be working, and i am not sure this has something to do with the fact that the table is created by js.
// Adding Cosignment number
$('#parcel-overview').append(
// Add main tables which will display the added packages
'<table border="1">' +
'<thead><tr><th>Packages</th><th>Weight</th> <th>Vol Weight</th><th>Charge Weight</th> <th>Price</th></tr></thead><tbody id="parcels-added-overview"></tbody> ' +
'</table>'
);
for (var i = 0; i < packageNum; i++) {
var ii = (i + 1).toString();
// Working out volemetric weight
wei = $('#added-parcels #weighting-' + ii + ' input').val();
len = $('#added-parcels #lengthing-' + ii + ' input').val();
wid = $('#added-parcels #widthing-' + ii + ' input').val();
hei = $('#added-parcels #heighting-' + ii + ' input').val();
//Calculating Volumetric weight
tot = ((len * wid * hei) / 5000).toFixed(1);
pri = (tot * 23).toFixed(2);
chr = (tot * 12).toFixed(2);
$('#parcels-added-overview').append(
'<tr>' +
'<td class="par-id">' + (i + 1).toString() + '</td>' +
'<td class="par-weight">' + wei.toString() + ' kg\'s</td>' +
'<td class="par-vol-weight">' + tot.toString() + ' kg\'s</td>' +
'<td class="par-charge-weight">R ' + chr.toString() + '</td>' +
'<td class="par-price">R ' + pri.toString() + ' </td>' +
'</tr>'
);
}
I then want to add the values of that table that have been added dynamically to an object array that is then added to the primary object array.
var parcelObj = new Object();
$.each($('#parcels-added-overview tr'),function (index) {
parcelObj.parcelId = $(this).children('.par-id').text();
parcelObj.totalWeight = $(this).children('.par-weight').text();
parcelObj.volWeight = $(this).children('.par-vol-weight').text();
parcelObj.chargeWeight = $(this).children('.par-charge-weight').text();
parcelObj.overallPrice = $(this).children('.par-price').text();
parcelsArr.push(parcelObj);
});
consignmentObj.parcels = parcelsArr;
consignmentsArr.push(consignmentObj);
I might be a n00b , but this code (although i think its fairly verbose ) should work.
Does the $(this).children not identify directly on each() row that it is iterating over?
When i add console.log(consignmentsArr); i get the array within the object as it should be but the values for the parcel object are just repeating the last row of the table.
1: Object
deliName: ""
deliStreet: ""
docType: "Document"
insurance: "None"
parcels: Array[2]
0: Object
chargeValue:"R34.43"
overallPrice:"R43.54"
parcelId:"2"
totalWeight:"65 kg's"
volWeight:"63 kg's"
1: Object
chargeValue:"R34.43"
overallPrice:"R43.54"
parcelId:"2"
totalWeight:"65 kg's"
volWeight:"63 kg's"
Why can I not get the first row values to be added to parcels[0]?
Thanks
Try to declare parcelObj object inside the function.
$.each($('#parcels-added-overview tr'),function (index) {
var parcelObj = new Object();
parcelObj.parcelId = $(this).children('.par-id').text();
parcelObj.totalWeight = $(this).children('.par-weight').text();
parcelObj.volWeight = $(this).children('.par-vol-weight').text();
parcelObj.chargeWeight = $(this).children('.par-charge-weight').text();
parcelObj.overallPrice = $(this).children('.par-price').text();
parcelsArr.push(parcelObj);
});
consignmentObj.parcels = parcelsArr;
consignmentsArr.push(consignmentObj);

Categories