I have a data() object containing some json.
Is there a way I can loop through the object and grab each parts key and value?
This is what I have so far:
function getFigures() {
var propertyValue = getUrlVars()["propertyValue"];
$.getJSON(serviceURL + 'calculator.php?value=' + propertyValue, function(data) {
figures = data.figures;
$.each(figures, function(index, figure) {
$('#figureList').append('<li> index = ' + data.figures.figure + '</li>');
});
});
$('#figureList').listview('refresh');
}
The json looks like this:
{"figures":{"value":"150000","completion":"10.00","coal":"32.40","local":"144.00","bacs":"35.00","landRegistry":"200.00","solFee":"395.00","vatOnSolFees":79,"stampDuty":1500,"total":2395.4}}
Apologies if its simple, I'm new to jQuery and couldn't find anything on SO that helped.
You can get the key and value like this
$.each(data.figures, function(key, val) {
console.log('Key: ' + key + ' Val: ' + val)
});
So change your code to
$('#figureList').append('<li>'+ index + ' = ' + figure + '</li>');
Demo: http://jsfiddle.net/joycse06/ERAgu/
The parameters index and figure contains the parameter name and value. I think that you want to concatenate the parameters into the string:
$('#figureList').append('<li>' + index + ' = ' + figure + '</li>');
An alternative is to create the list item element and set the text of it, that would also work if the text contains any characters that need encoding:
$('#figureList').append($('<li/>').text(index + ' = ' + figure));
function getFigures() {
var propertyValue = getUrlVars()["propertyValue"];
$.getJSON(serviceURL + 'calculator.php?value=' + propertyValue, function(data) {
$.each(data['figures'], function(index, val) {
here grab "val" is key
$.each(data['figures'][index], function(col, valc) {
here grab "col" is value
}
}
}
bye
Related
I have this array and I need to get the public_id and format values
{"resources":[{"public_id":"samples/3_zm3ex0","version":1643650862,"format":"jpg","width":4000,"height":3000,"type":"upload","created_at":"2022-01-31T17:41:02Z"},{"public_id":"mggvuz0xisg2nzkldbvx","version":1643520511,"format":"jpg","width":500,"height":549,"type":"upload","created_at":"2022-01-30T05:28:31Z"},{"public_id":"samples/cloudinary-group","version":1643517184,"format":"jpg","width":3000,"height":1526,"type":"upload","created_at":"2022-01-30T04:33:04Z"}],"updated_at":"2022-01-31T18:28:07Z"}
I try to do it like this but without success
$(document).ready(function() {
$("#fetch").click(function(event) {
$.getJSON('https://res.cloudinary.com/dkx20emez/image/list/dom.json', function(emp) {
$('#display').html('<p> Name: ' + emp.resources.public_id + '</p>');
$('#display').html('<p> Name: ' + emp.resources.format + '</p>');
});
});
});
I appreciate your help
The ressources attributes is an array so you have to loop each element in it. Your code should be like this :
$(document).ready(function() {
$("#fetch").click(function(event) {
$.getJSON('https://res.cloudinary.com/dkx20emez/image/list/dom.json', function(emp) {
//the attribute resource is an array so you have to loop each element in it
emp.resources.forEach(function(element){
var publicid = element.public_id;
var format = element.format;
$('#display').append('<div><p> Name: ' + publicid + '</p><p> Name: ' + format + '</p></div>');
});
});
});
});
I'm trying to loop through an array using contains, but even if the value isnt it there it still appears true. The array is a list of checkboxes
function CheckBoxLogic(QId, Valuearray, UnCheckedValueArray) {
var CheckedChildArray = Valuearray;
var UnCheckedChildArray = UnCheckedValueArray;
$('.AnswerFunctions').each(function () {
//Get ParentID from child control
var ParentQuestionId = $(this).attr('ParentQuestionId');
//Get ParentValue from child control
var ParentQuestionValue = $(this).attr('ParentQuestionValue');
var QuestionId = $(this).attr('QuestionId');
if (ParentQuestionId === QId) {
if ($(CheckedChildArray + ":contains('" + ParentQuestionValue + "')")) {
$('#' + QuestionId + '-Question').removeClass('d-none');
}
//if ($(UnCheckedChildArray + ":contains('" + ParentQuestionValue + "')")) {
// $('#' + QuestionId + '-Question').addClass('d-none');
// };
}
});
}
}
That's not how you loop through an array. (At its simplest, what exactly do you expect [] + ":contains('" to be? You can't meaningfully concatenate a string and an array like that.)
If you want to check if an array contains a value, you can use the includes method. For example:
if (CheckedChildArray.includes(ParentQuestionValue)) {
$('#' + QuestionId + '-Question').removeClass('d-none');
}
I update the value of a select input like so:
$('.filter').change(function() {
$.post('/schedules', { sid: $(this).val() }, function(result) {
$.each(result, function(k, v) {
var least = 0;
if(v.sort_c > least) {
$('.filter2').append('<option value="' + v.id + '.' + 'test_value' + '">' + v.name + '</option>');
least = v.sort_c;
}
});
});
});
After this jQuery runs I need to then get the value of $('.filter2'). When I try to do $('.filter2').val() it returns nothing.
Why is this happening?
You probably want to find the value of the selected option inside your select named filter2. Try this:
$('.filter2 option:selected').val();
After this jQuery runs seems to imply that you're not taking into account the asynchronous(AJAX) request involved. The following should give you the correct value of .filter2:
$('.filter').change(function() {
$.post('/schedules', { sid: $(this).val() }, function(result) {
$.each(result, function(k, v) {
var least = 0;
if(v.sort_c > least) {
$('.filter2').append('<option value="' + v.id + '.' + 'test_value' + '">' + v.name + '</option>');
least = v.sort_c;
}
});
console.log( $('.filter2').val() ); //<========
});
});
However, since I don't see you setting any of the new options with a selected attribute, I wonder what value you expect to get that you would not get before the change.
I want to navigate each property in the JSON below in JavaScript. The below JSON contains two records for reference but in real time will have numerous such records.
{"Record_0":[{"Status":"CREATED","CreatorLoginId":"sandhya","Name":"G1"}],"Record_1":[{"Status":"CREATED","CreatorLoginId":"San","Name":"G2"}]}
I want to get the values of the fields "Status", "CreatorLoginId" and "Name" to assign them to something else.
How should I do it?
var myJSON = JSON.parse('{"Record_0":[{"Status":"CREATED","CreatorLoginId":"sandhya","Name":"G1"}],"Record_1":[{"Status":"CREATED","CreatorLoginId":"San","Name":"G2"}]}');
for(var pr in myJSON)
{
console.log(myJSON[pr][0].Status);
console.log(myJSON[pr][0].CreatorLoginId);
console.log(myJSON[pr][0].Name);
}
Print how? If you mean output to the js console it would be
for (index in object) {
console.log(index + ': ' + object[index]);
}
If you mean add it to a web page, just replace console.log with a little markup:
var parent = document.getElementById('parentID');
for (index in object) {
parent.innerHTML += index + ': ' + object[index] + '<br>';
}
For nested objects (including arrays)
function print(object, parent) {
for (index in object) {
if (typeof object[index] == 'object') {
print(object[index});
}
parent.innerHTML += index + ': ' + object[index] + '<br>';
}
}
EDIT: don't forget to JSON.parse(): the string first before iterating
//Iterating through the groups
for (var currentRecord in groupInformation)
{
store.data.items.push({serial: {}, groupName: {}, createdBy: {}, status: {} });
store.data.items[iNoOfGroups].serial = iNoOfGroups + 1;
store.data.items[iNoOfGroups].groupName = groupInformation[currentRecord][0].Name;
store.data.items[iNoOfGroups].createdBy = groupInformation[currentRecord][0].CreatorLoginId;
store.data.items[iNoOfGroups].status = groupInformation[currentRecord][0].Status;
iNoOfGroups++;
}
var myJSON = JSON.parse('{"Record_0":[{"Status":"CREATED","CreatorLoginId":"sandhya","Name":"G1"}],"Record_1":[{"Status":"CREATED","CreatorLoginId":"San","Name":"G2"}]}');
for(var key in myJSON){
console.log(myJSON[key][0].Status);
console.log(myJSON[key][0].CreatorLoginId);
console.log(myJSON[key][0].Name);
}`
my list result display I need to create spaces or group them between my displayed list result I tried using the break tags but they don't work
function GetProductDetails(barcodeId, coords)
{
$.getJSON("api/products/?barcodeId=" + barcodeId + "&latitude=" + coords.latitude + "&longitude=" + coords.longitude)
.done(function (data)
{
$('#result').append(data.message)
console.log(data)
var list = $("#result").append('<ul></ul>').find('ul');
$.each(data.results, function (i, item)
{
if(data.results == null)
{
$('#result').append(data.message)
}
else
{
list.append('<li>ShopName :' + item.retailerName + '</li>');
list.append('<li>Name : ' + item.productName + '</li>');
list.append('<li>Rand :' + item.price + '</li>');
list.append('<li>Distance in Km :' + item.Distance + '</li>');
}
});
$("#result").append(ul);
});
}
list.append('<li><b>ShopName</b><p>' + item.retailerName + '</p></li>');
list.append('<li><b>Name</b><p>' + item.productName + '</p></li>');
list.append('<li><b>Rand</b><p>' + item.price + '</p></li>');
list.append('<li><b>Distance</b><p>' + item.Distance + '</p></li>');
Pretty sure that list is always going to be the first ul in your results box, no matter how many you actually add. Also, your final $("#result").append(ul) is an error because there is no ul variable.
Try this:
var list = document.getElementById('result').appendChild(document.createElement('ul'));
data.results.forEach(function(item) {
list.appendChild(document.createElement('li'))
.appendChild(document.createTextNode("ShopName : "+item.retailerName));
list.appendChild(document.createElement('li'))
.appendChild(document.createTextNode("Name : "+item.productName));
list.appendChild(document.createElement('li'))
.appendChild(document.createTextNode("Rand : "+item.price));
list.appendChild(document.createElement('li'))
.appendChild(document.createTextNode("Distance in Km : "+item.Distance));
});
Vanilla JS may be more verbose to write, but it is immensely easier to understand and use, once you get past that mental block ;) Of course, there's nothing to stop you creating a helper function:
function addLIwithText(ul,text) {
ul.appendChild(document.createElement('li'))
.appendChild(document.createTextNode(text));
}
Then your loop contents become:
addLIwithText(list,"ShopName : "+item.retailerName);
// and so on