Trying to iterate over - javascript

I'm trying to iterate through a JSON object and wrap each item in the array in an li tag.
Here is my JSON structure
var classYear = {
"1921": [
'name1', 'name2', 'name3', 'name4'
],
"1933": [
'name5', 'name6', 'name7', 'name8'
],
"1943": [
'name9', 'name10', 'name11', 'name12', 'name13'
]
};
Here is my javascript
var container = document.getElementById('classYearContainer');
function classYearOutput(yClass, yId, listId, key, name) {
return '<div class="'+ yClass +'" id="'+ yId +'">' +
'<h4>' + key + '</h4>' +
'<ul id="'+ listId +'">' + name + '</ul>' +
'</div>';
}
function nameList(name) {
return '<li>' + name + '</li>';
}
for(var year in classYear) {
container.innerHTML += classYearOutput(
'category',
'y-' + year,
year + '-list',
year,
nameList(classYear[year])
);
}
With this setup my output is returning all the names in one li as opposed to separate li tags. Strangely, when I console.log I get the expected result, but when I return it puts all names in the same li.
Thanks for any help.

classYear[year] is an array, and you're passing it to the nameList function.
You have to iterate in that function as well
function nameList(name) {
var html = '';
for (var i=0; i<name.length; i++) {
html += '<li>' + name[i] + '</li>';
}
return html;
}

The issue is your passing the array into name list, you'll need to loop through the array and create an li for each name.
function nameList(names) {
var out = "";
names.forEach(function (el) {out += "<li>" + el + "</li>";});
return out;
}
Fiddle: http://jsfiddle.net/noy3dshx/

function nameList(names) {
return names.map(function(name) {
return '<li>' + name + '</li>';
});
}
Names is an array, so you need to iterate over that instead you are essentially calling the toString method of the array which is doing it's best and giving you a comma seperated list of the contents (e.g. console.log(['a', 'b', 'c'].toString()); or console.log('' + ['a', 'b', 'c']);)

Related

Add items to JSON object

I'm picking up a JSON object using a promise:
var x = get();
x.done(function(data) {
for(var i in data) {
}
});
which is returning this data when i do console.log(data);
[{…}]
0:
customer: "9028"
data:
active: "1"
customer: "9028"
description: ""
id: "13717"
inherited: "0"
name: "Out of Hours"
priority: "1"
shared: "0"
sound: ""
__proto__: Object
voip_seq: "4"
__proto__: Object
length: 1
__proto__: Array(0)
so that is working fine, but within my for loop, I want to add 2 items to data
I tried adding this into my .done
var obj = { name: "Light" };
data.push(obj);
But that didn't add to data
My for loop looks like this:
for(var i in data) {
var m = '<option value="' + data[i].data.id + '"'
if(data[i].data.id == selected_val) {
m += ' selected="selected"';
}
m += '>' + data[i].data.name + '</option>';
$('#' + value_element_id).append(m);
}
If you want to add two more items to your select, you simply need to push new objects into your data array before your loop starts. The objects must contain the structure and properties ("name" and "id" within a "data" sub-property) matching the JSON coming from the Promise, so that your loop code can process them.
In the simplest case, it could be as straightforward as
x.done(function(data) {
data.push({ "data": { "name": "light", "id": 1234 } });
data.push({ "data": { "name": "dark", "id": 5678 } });
for(var i in data) {
var m = '<option value="' + data[i].data.id + '"'
if (data[i].data.id == selected_val) {
m += ' selected="selected"';
}
m += '>' + data[i].data.name + '</option>';
$('#' + value_element_id).append(m);
}
});
Demo: https://jsfiddle.net/a286b7fw/1/
In this case I think data is not an array so it hasn't .push() method. You can add property to object like this:
for(var i in data) {
var m = '<option value="' + data[i].data.id + '"'
if(data[i].data.id == selected_val) {
m += ' selected="selected"';
}
m += '>' + data[i].data.name + '</option>';
$('#' + value_element_id).append(m);
// here it will add obj to data
var obj = {name: "Light"};
data = {
...data,
obj
}
}

Array list display online one result from json

I wrote this code and it works:
function getJsonResult(retrieve) {
var result = retrieve.results;
for (var i = 0; i < result.length; i++) {
responseJson.push({ id: result[i].id, title: result[i].title });
var search = '<a id="' + result[i].id + '">' + result[i].title + '</a><br/>';
document.write(search);
}
}
When I tried to display the results in a div, I change the last line with:
$("#divId").html(search);
But it only displays the first result. How can I make the whole list appear?
That happened because you're overriding the search variable in every iteration :
var search = '<a id="' + result[i].id + '">' + result[i].title + '</a><br/>';
You need to declare the search variable outside of the loop then append the string in every iteration like :
function getJsonResult(retrieve) {
var result = retrieve.results;
var search = "";
___________^^^^
for (var i = 0; i < result.length; i++) {
responseJson.push({ id: result[i].id, title: result[i].title });
var search += '<a id="' + result[i].id + '">' + result[i].title + '</a><br/>';
___________^^
document.write(search);
}
}
Then finally you could put your variable content to the div :
$("#divId").html(search);
$('#divId').append(search);
This appends the element included in search to the div element.

How can iterate over JSON object and print its properties and their values?

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

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

Loop through jquery data() object to get keys and values

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

Categories