Unable to loop through JSON Data [duplicate] - javascript

This question already has answers here:
I keep getting "Uncaught SyntaxError: Unexpected token o"
(9 answers)
Closed 7 years ago.
I have the following Json data (Please see the image). I am trying to extract the data using the below jQuery code and it's not working. Please help.
var items = [];
$.each($.parseJSON(OnePointData), function (key, val) {
items.push("<li id='" + key + "'>" + val + "</li>");
$.each(key, function(key2, val2) {
items.push("<li id='" + key2 + "'>" + val2 + "</li>");
});
});
console.log(items);
Here is an image of my console:
And here is additional code from my implementation:
$.getJSON("/Home/GetOnePointData", { Address: ui.item.value },function(OnePointData) {
console.log(OnePointData);
var items = [];
var items2 = [];
$.each($.parseJSON(OnePointData), function (key, val) {
items.push("<li id='" + key + "'>" + val + "</li>");
$.each(key, function (key2, val2) {
items2.push("<li id='" + key2 + "'>" + val2 + "</li>");
});
});
console.log(items2);
});
If i run the loop once then i get the following result.
The data is in the following format:
{"GetQuestions":{"s1":"Q1,Q2","s2":"Q1,Q2,Q3","s3":"Q1,Q2,Q4","s4":"Q1,Q2,Q4,Q6"},
"GetQuestions2":{"s1":"Q1,Q2","s2":"Q1,Q2,Q3","s3":"Q1,Q2,Q4","s4":"Q1,Q2,Q4,Q6"}}

As #Barmar says $.getJSON calls $.parseJSON automatically. So, just try removing $.parseJSON function:
$.getJSON("/Home/GetOnePointData", { Address: ui.item.value}, function(OnePointData) {
console.log(OnePointData);
var items = [];
var items2 = [];
$.each(OnePointData, function (key, val) {
items.push("<li id='" + key + "'>" + val + "</li>");
$.each(val, function (key2, val2) {
items2.push("<li id='" + key2 + "'>" + val2 + "</li>");
});
});
console.log(items2);
});
This is an example using data structure posted by you and it works.
var OnePointData = {"GetQuestions":{"s1":"Q1,Q2","s2":"Q1,Q2,Q3","s3":"Q1,Q2,Q4","s4":"Q1,Q2,Q4,Q6"},
"GetQuestions2":{"s1":"Q1,Q2","s2":"Q1,Q2,Q3","s3":"Q1,Q2,Q4","s4":"Q1,Q2,Q4,Q6"}};
var items = [];
var items2 = [];
$.each(OnePointData, function (key, val) {
items.push("<li id='" + key + "'>" + val + "</li>");
$.each(val, function (key2, val2) {
items2.push("<li id='" + key2 + "'>" + val2 + "</li>");
});
});
console.log(items);
console.log(items2);
Output:
["<li id='GetQuestions'>[object Object]</li>", "<li id='GetQuestions2'>[object Object]</li>"]
["<li id='s1'>Q1,Q2</li>", "<li id='s2'>Q1,Q2,Q3</li>", "<li id='s3'>Q1,Q2,Q4</li>", "<li id='s4'>Q1,Q2,Q4,Q6</li>", "<li id='s1'>Q1,Q2</li>", "<li id='s2'>Q1,Q2,Q3</li>", "<li id='s3'>Q1,Q2,Q4</li>", "<li id='s4'>Q1,Q2,Q4,Q6</li>"]

Related

I need a way to keep selected combobox values after page refresh

I have a number of comboboxes they all look like this:
<select name="cb1" size="1" id="kuz1" style="position:absolute;left:19px;top:96px;width:144px;height:69px;z-index:2;">
<option>Пусто</option>
</select>
then i obtain options for them from txt file using a simple js script.
I need a way to store selected information and keep it even if page is refreshed. I tried to use localstorage and cookie options, but they didn't work for some reason.
i tried to set variables like this var kuz1var=document.getElementById('kuz1').value;
but console always returns as "undefined"
I need somebody's advice to resolve this issue
Here is how i managed to obtain values for comboboxes
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script>
$.get("мм.txt", function (data) {
var lines = data.split('\n').map(function(line){
return line.trim();
});
var select = $("select[name=cb1]")
var optionCounter = 0;
var currentGroup = "";
lines.forEach(function(line){
if(line.endsWith(" -")){
currentGroup = line.substring(0, line.length - 2);
optionCounter = 0;
select.append("<optgroup id='" + currentGroup + "' label='" + currentGroup + "'>")
} else if(line === ""){
select.append("</optgroup>");
} else {
select.append("<option type='checkbox' id='"
+ (currentGroup + optionCounter) + "' name='"
+ (currentGroup + optionCounter) + "' value='"
+ line + "'>" + line + "</option>");
}
});
console.log(lines);
});
</script>
For some reason the right answer was deleted, so here's the answer
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script>
$.get("мм.txt", function (data) {
var lines = data.split('\n').map(function(line){
return line.trim();
});
var select = $("select[name=cb1]")
var optionCounter = 0;
var currentGroup = "";
lines.forEach(function(line){
if(line.endsWith(" -")){
currentGroup = line.substring(0, line.length - 2);
optionCounter = 0;
select.append("<optgroup id='" + currentGroup + "' label='" + currentGroup + "'>")
} else if(line === ""){
select.append("</optgroup>");
} else {
select.append("<option type='checkbox' id='"
+ (currentGroup + optionCounter) + "' name='"
+ (currentGroup + optionCounter) + "' value='"
+ line + "'>" + line + "</option>");
}
});
// Get the selected value from local storage
var cb1val = localStorage.getItem("cb1val");
if (cb1val) {
select.val(cb1val);
}
select.on("change", function () {
// Save the selected value to local storage
localStorage.setItem("cb1val", select.val());
});
console.log(lines);
});
</script>

How to parse JSON data in javascript when the property name is unknown

I am parsing JSON data and property name is unknown. I am sharing my code please tell me how can i get all data with unknown property
datas.data.videoGroup.past after that please use a loop
$.each(datas.data.videoGroup.past.Algebra, function(i, v) {
var hash5 = v.id;
var link = hash5;
var tblRows = "<tr>" + "<td>" + v.title + "</td>" + "<td>" + 2 + ' ₹' + "</td>" + "<td><a target='_blank' href='" + link + "'>" + "WATCH/DOWNLOAD" + "</a></td>" + "</tr>";
$(tblRows).appendTo("#userdata");
});
$.each(datas.data.videoGroup.past["Number System"], function(i, v) {
I put Number System and Algebra manually but i can't do it with each subject and for each teacher.
Either iterating over the properties using for...in loop or getting the list of all the known keys on the object using the Object.keys() method; which returns an array containing all the keys which can be mapped over.
const obj = {
a: 'hello',
b: 'world',
c: 'test',
};
for (const prop in obj) {
console.log(`${prop}: ${obj[prop]}`);
}
// "a: 1"
// "b: 2"
// "c: 3"
console.log(Object.keys(obj));
// ["a", "b", "c"]
#
Something like -
for( const prop in datas.data.videoGroup.past) {
$.each(datas.data.videoGroup.past[prop], function(i, v) {
var hash5 = v.id;
var link = hash5;
var tblRows = "<tr>" + "<td>" + v.title + "</td>" + "<td>" + 2 + ' ₹' + "</td>" + "<td><a target='_blank' href='" + link + "'>" + "WATCH/DOWNLOAD" + "</a></td>" + "</tr>";
$(tblRows).appendTo("#userdata");
});
}

JavaScript $.each json is not defined

I have a string of JSON
msg = {d: "[{"ID":1,"IndentDate":"30/07/2018","EmpCode":"4000…er":"sef"}]
I wish to append my table but its showing row is undefined
$.each(msg, function(i, row) {
$("#autoTable").append("<tr><td>" + row['IndentDate'] + "</td><td>" + row['EmpCode'] + "</td></tr>");
})
I tried
$.each(json, function (i, msg) {
$("#autoTable").append("<tr><td>" + msg.IndentDate + "</td><td>" + msg.EmpCode + "</td></tr>");
})
too.please help
this thing worked..hope it helps others too..thanks for the help guys
var jsonString = JSON.parse(msg.d);
jsonString.forEach(function (row) {
$("#autoTable").append("" + row.IndentDate + "" + row.EmpCode + " ");
});

Appending string to value of array

Hi Im populating select > options using my json using below code. Here my doubt is I want to add custom attribute only if value is "IN". Anyone can help to achieve this
$.each( data, function( i, val ) {
items.push( "<option value='" + val.countryCode + "'>" + val.countryName + "</option>" );
});
Try something like this
$.each( data, function( i, val ) {
items.push( "<option value='" + val.countryCode +( val.countryCode == "IN" ? "data-attr = 'value'" : "" ;) "'>" + val.countryName + "</option>" );
});
Currently it's only possible with a if condition. You can increase speed by breaking on the first found result, but you need to use a for-loop:
for(var i=0;i<countryArr.length;i++) {
if(countryArr[i].countryCode === "IN") {
items.push( "<option value='" + countryArr[i].countryCode + "'>" + countryArr[i].countryName + "</option>" );
break;
}
});
If you want to use forEach see this post.. But a some expression might be easier:
countryArr.some(function(data) {
var check=countryArr[i].countryCode ==="IN";
if(check) {
items.push("<option value='" + data.countryCode + "'>" + data.countryName + "</option>");
}
return check; //some stops, if it returns true
});
ECMA6 will introduce a find method so you can shortcut this:
items.push(countryArr.find(function(data) {
return data.countryCode === "IN";
});
$.each( data, function( i, val ) {
if(val.countryCode !='IN') {
items.push( "<option value='" + val.countryCode + "'>" + val.countryName + "</option>" );
}
else {
items.push( "<option data-id=1 value='" + val.countryCode + "'>" + val.countryName + "</option>" );
}
});
If I understand your question correctly:
$.each( data, function( i, val ) {
items.push( "<option "+ (val.countryCode === "IN" && "data-id=1" || "") + " value='" + val.countryCode + "'>" + val.countryName + "</option>" );
});`

Create rowspans with jquery

I append the data from a json-object to a table:
var array1 = $.map(data, function (field, i)
{
return '<tr><td>' + field.date + '</td><td>' + field.art + '</td><td class="san' + field.art +'">' + field.text + '</td></tr>';
});
$('#TableBody').append(array1.join(''));
Actually this works pretty good and i get a output like this:
<tbody id="TableBody">
<tr><td>18.02.2014</td><td>D</td><td class="sanD">Was soll ich sagen</td></tr>
<tr><td>18.02.2014</td><td>DD</td><td class="sanDD">hallo</td></tr>
<tr><td>17.02.2014</td><td>R</td><td class="sanR">Erster Versuch</td></tr>
</tbody>
But i would like to have such an output: Means that same field.date have only one row:
<tbody id="TableBody">
<tr><td rowspan="2">18.02.2014</td><td>D</td><td class="sanD">Was soll ich sagen</td></tr>
<tr><td>DD</td><td class="sanDD">hallo</td></tr>
<tr><td>17.02.2014</td><td>R</td><td class="sanR">Erster Versuch</td></tr>
</tbody>
How can i achieve this? Thanks
Fiddle: http://jsfiddle.net/V2mmw/2/
Here is a function that does what you want:
function mergeSameDates() {
var $firstItem,
sameCount = 0;
$("#TableBody tr td:nth-child(1)").each(function (index, item) {
var $item = $(item);
if ($firstItem === undefined || $item.text() !== $firstItem.text()) {
$firstItem = $item;
sameCount = 1;
} else {
sameCount += 1;
$firstItem.attr("rowspan", sameCount);
$item.remove();
}
});
}
Here is an updated demo fiddle.
I think that you need something like this, but i used $.each function:
var html = "";
var arr = new Array();
$.each(data, function (i, field) {
var rowspanTest = $.grep(data, function (elem) {
return elem.date === field.date;
}).length;
if(jQuery.inArray( field.date, arr ) == -1){
html += '<tr><td rowspan=' + rowspanTest + '>' + field.date + '</td><td>' + field.art + '</td><td class="san' + field.art +'">' + field.text + '</td></tr>';
arr.push(field.date);
}else{
html += '<tr><td>' + field.art + '</td><td class="san' + field.art +'">' + field.text + '</td></tr>';
}
});
$('#TableBody').append(html);
Demo JSFiddle

Categories