Loop through JSON array, display two and then Count - javascript

Okay, so I'm a JSON noob with only basic jQuery knowledge and I've looked all over for a solution and can't find one. Any help is greatly appreciated.
I need to:
1) loop through a JSON array (working)
2) display the first two results for "mbrname"
3) then display a count for the rest of the results.
I am successfully looping through and displaying ALL mbrname results. But somehow I need to only display the first two and if there are more display "+ # others"
Here's a screenshot of what the final product should look like:
Here's what my code produces now:
Here's my JSON:
{
"messages":{
"message":[
{
"date-time":"June 2, 2013 12:22 pm",
"subject":"This is the message subject",
"msg-string":"001",
"newmsg":"true",
"attach":"shop-cart",
"recipient":[
{
"mbrname":"D. Craig",
"mbr-href":"#craig"
},
{
"mbrname":"N. McCoy",
"mbr-href":"#mccoy"
},
{
"mbrname":"J. Smith",
"mbr-href":"#smith"
},
{
"mbrname":"B. Wardlaw",
"mbr-href":"#wardlaw"
}
]
},
{
"date-time":"May 23, 2013 12:22 pm",
"subject":"This is a great subject",
"attach":"none",
"msg-string":"002",
"newmsg":"true",
"recipient":[
{
"mbrname":"D. Craig",
"mbr-href":"#craig"
},
{
"mbrname":"N. McCoy",
"mbr-href":"#mccoy"
}
]
},
{
"date-time":"May 11, 2013 12:22 pm",
"subject":"Interested in your tomatoes",
"attach":"shop-cart",
"msg-string":"003",
"newmsg":"false",
"recipient":[
{
"mbrname":"J. Smith",
"mbr-href":"#smith"
}
]
}
]
}
}
Here's my jquery just for the "mbrname" section which successfully pulls in the names and appends them to my HTML:
$.each (message.recipient, function (message, recipient) {
var mbrPart = recipient.mbrname + ', ';
var currentUser = $('#' + newID + ' .name');
$(currentUser).append(mbrPart);
});
Thanks in advance for any help!

I'd keep it simple, no need to do any looping:
var recipientString = message.recipient[0].mbrname;
var count = message.recipient.length;
if (count > 1)
recipientString += ', ' + message.recipient[1].mbrname;
if (count > 2)
recipientString += ' + ' + (count - 2) + ' others';
$('#' + newID + ' .name').append(recipientString);

Something like this should work.
var count = 0;
$.each (message.recipient, function (message, recipient) {
if(count<2){
var mbrPart = recipient.mbrname + ', ';
var currentUser = $('#' + newID + ' .name');
$(currentUser).append(mbrPart);
}
count++;
});
$(currentUser).append(" + " + count-2 + " Others");

Related

How to make a loop with a Jquery subarray Json?

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

How can I fix variables of an array of objects being undefined when being imported from a json file?

I am creating a website to practice my coding on and I came across a problem while doing so. I am trying to import data from a json file with a forloop and the variables came back as undefined. I think it has to do with the i variable in the foreach, but I could be wrong. Any help is much appreciated. Thanks!
<script>
$.getJSON('package.json', function(data){
for(var i in data)
{
var username = i.username;
var value = i.value;
var tokens= i.tokens;
$(".list-group").append('<li>' + username + ' has deposited $' + value + ' in ' + tokens + ' tokens</li>');
}
});
</script>
And here is a copy of the json file
{
"u1":
{
"username": "Username1",
"tokens": 2,
"value": 26
},
"u2":
{
"username": "Username2",
"tokens": 4,
"value": 292
},
"u3":
{
"username": "Username3",
"tokens": 10,
"value": 127
},
"u4":
{
"username": "Username4",
"tokens": 3,
"value": 12
}
}
if data is an array, i will be an Integer-value string of the index.
You'll want data[i].username, data[i].value, data[i].tokens instead
if data is an object, you don't need to iterate through it
You'll want data.username, data.value, data.tokens instead
if the data from json is array of object use it;
<script>
$.getJSON('package.json', function(data){
for(var i in data)
{
var username = data[i].username;
var value = data[i].value;
var tokens= data[i].tokens;
$(".list-group").append('<li>' + username + ' has deposited $' + value + ' in ' + tokens + ' tokens</li>');
}
});
</script>
else use it
<script>
$.getJSON('package.json', function(data){
var username = data.username;
var value = data.value;
var tokens= data.tokens;
$(".list-group").append('<li>' + username + ' has deposited $' + value + ' in ' + tokens + ' tokens</li>');
});
</script>

What is the best way to iterate through a JSON object and print elements to the screen?

I'm just trying to learn the most efficient way to manipulate JSON data and slap it up on the screen. I'm a noob so try to break your answer down clearly if you can. Javascript and jQuery solutions welcome. Something like this:
Meats
NY Strip $20.00
Ribeye $19.00
Vegetables
Kale $4.00
Sunchokes $3.20
This is the JSON object (could it be rewritten more efficiently?):
var foods = {
"category":{
"Meats":[
{
"product":"NY Strip",
"price":20.00,
"cost":14.00,
"total sold": 3
},
{
"product":"Ribeye",
"price":20.00,
"cost":14.00,
"total sold": 6
}
],
"Vegetables":[
{
"product":"Kale",
"price":4.00,
"cost":2.00,
"total sold": 10
},
{
"product":"Sunchokes",
"price":3.20,
"cost":1.00,
"total sold": 5
}
]
}
}
Here is my attempt: (wish I knew of a way to incorporate the category titles into the loops instead of hard coding them.)
<h3>Meats</h3>
<script>
for(key in foods.category.Meats){
document.write("<li>" + foods.category.Meats[key].product + " $" + foods.category.Meats[key].price + "</li>");
}
</script>
<h3>Vegetables</h3>
<script>
for(key in foods.category.Vegetables){
document.write("<li>" + foods.category.Vegetables[key].product + " $" + foods.category.Vegetables[key].price + "</li>");
}
</script>
This will iterate through your entire object.
var category = foods.category
for(var cat in category) {
if(category.hasOwnProperty(cat)) {
category[cat].forEach(function(item) {
console.log(item);
// Do stuff here
});
}
}
Here is another approach:
Object.keys(foods.category).forEach(function(category) {
foods.category[category].forEach(function(item) {
console.log('do stuff with', item);
});
});
Ah, thanks y'all.
var category = foods.category
for(var key in category) {
if(category.hasOwnProperty(key)) {
category[key].forEach(function(item) {
if(document.getElementById(key) === null){
document.write("<h4" + " id='" + key + "'" + ">" + key + "</h4>")
}
document.write("<li>" + item.product + "</li>");
});
}
}

go to the next index of an array using onclick in Javascript

I apologize in advance if I'm vague or my code is difficult to understand, I'm still learning this stuff. I'm trying to display information that is stored within an array. I want to display this information when a button is clicked and when it is clicked again, the next index in the array displays its information..
I need help setting up a function that advances to the next index of the array. Thanks!
(function(){
var students =[ //array of information
{name:'john',
address:{
address:'821 Imaginary St',
city:'Chicago',
state:'Il'},
gpa:[4.0,3.5,3.8]},
{name:'jim',
address:{
address:'127 fake Rd',
city:'Orlando',
state:'Fl'},
gpa:[2.5,3.3,3.6]}];
var redBut = document.querySelector('.buttonred');
redBut.onclick = getInfo;
var count = 0;
function getInfo(){
var stn = students[0];
if(count<3){
count++;
document.getElementById('name').innerHTML = 'Name: ' + stn.name; //this is what is to be displayed when the button is clicked
document.getElementById('address').innerHTML = 'Address: ' + stn.address.address + " " + stn.address.city + ", " + stn.address.state;
document.getElementById('gpa').innerHTML = 'GPA: ' + stn.gpa[0] +", " + stn.gpa[1] + ", " + stn.gpa[2];
document.getElementById('date').innerHTML = 'Date: ' + d.toLocaleDateString();
document.getElementById('gpaavg').innerHTML = 'Average GPA: ' + gpas;
}
}
I think you want: var stn = students[count];
And not: var stn = students[0];
(DOH!)

Why is jquery.each executing twice?

JSFiddle here: http://jsfiddle.net/xgTt2/3/
I have a $.each nested inside of a $.each, and I'm not sure why the second $.each is running twice. Any ideas?
var serverResponse = [{"Id":"aaa","OrderItems":[{"Id":1,"Description":"Salad"},{"Id":2,"Description":"Pizza"}]},{"Id":"bbb","OrderItems":[{"Id":3,"Description":"Salad"},{"Id":4,"Description":"Pizza"}]}];
$.each(serverResponse, function (index) {
var pos = serverResponse[index];
$('#placeholder').append('<p>' + pos.Id + '</p>')
$.each(pos.OrderItems, function (index) {
$('.orderitem').append('<p>' + this.Id +
' ' + this.Description + '</p>')
});
});
The above javascript is producing the following output:
aaa
1 Salad
2 Pizza
3 Salad
4 Pizza
bbb
3 Salad
4 Pizza
I want this:
aaa
1 Salad
2 Pizza
bbb
3 Salad
4 Pizza
Any idea what I'm doing wrong? Here's a working example of the problem: http://jsfiddle.net/xgTt2/3/
Near the end, you have two elements with the class orderitem. Using $('.orderitem').append() will append to both of them.
Instead, you want to append to the last element you created.
var $order_item = $('<p class="orderitem">' + pos.Id + '</p>');
$('#placeholder').append($order_item);
$.each(pos.OrderItems, function (index) {
$order_item.append('<p>' + this.Id +
' ' + this.Description + '</p>');
});
http://jsfiddle.net/xgTt2/4/
Here's the answer:
http://jsfiddle.net/7EmsX/
var serverResponse = [{
"Id": "aaa",
"OrderItems": [{
"Id": 1,
"Description": "Salad"
}, {
"Id": 2,
"Description": "Pizza"
}]
},
{
"Id": "bbb",
"OrderItems": [{
"Id": 3,
"Description": "Salad"
}, {
"Id": 4,
"Description": "Pizza"
}]
}];
$.each(serverResponse, function (index) {
var pos = serverResponse[index];
var $orderItem = $('<p class="orderitem">' + pos.Id + '</p>');
$orderItem.appendTo('#placeholder');
$.each(pos.OrderItems, function (index) {
$orderItem.append('<p>' + this.Id + ' ' + this.Description + '</p>')
});
});
When you select the .orderitem class, it is selected every pos item and inserting the sub items into it. You want to insert your sub-items only to the current pos item instead.
In second loop run, $('.orderitem') select all of your <p class="orderitem"></p>
Try below:
var serverResponse = [{"Id":"aaa","OrderItems":[{"Id":1,"Description":"Salad"},{"Id":2,"Description":"Pizza"}]},{"Id":"bbb","OrderItems":[{"Id":3,"Description":"Salad"},{"Id":4,"Description":"Pizza"}]}];
$.each(serverResponse, function (index) {
var pos = serverResponse[index];
var orderitemHTML = '';
orderitemHTML += '<p class="orderitem">' + pos.Id + '</p>';
$.each(pos.OrderItems, function (index) {
orderitemHTML += '<p>' + this.Id + ' ' + this.Description + '</p>';
});
$('#placeholder').append(orderitemHTML);
});

Categories