How to get the values inside a nested JSON array - javascript

Can someone let me know how can I access the values inside the option_value array? It's an array within another array.
I get the below error with my code:
TypeError: json.option[i].option_value[j] is undefined
My code
$(document).on("click", "[name^='option']", function () {
var value = $(this).val();
var parent_id = $(this)
.attr("name")
.replace(/[^\d.]/g, "");
$.ajax({
url:
"index.php?route=controlller/get_options&parent_id=" +
parent_id +
"&value=" +
value +
"&product_id=<?php echo $product_id; ?>",
type: "get",
dataType: "json",
success: function (json) {
if (json["option"]) {
for (i = 0; i < json["option"].length; i++) {
if (
json["option"][i]["type"] == "radio" ||
json["option"][i]["type"] == "checkbox"
) {
$("#ioption" + json["option"][i]["product_option_id"])
.find("input")
.prop("checked", false);
for (j = 0; j <= json["option"][i]["option_value"].length; j++) {
$("#ioption" + json["option"][i]["product_option_id"])
.find(
"input[value='" +
json["option"][i]["option_value"][j][
"product_option_value_id"
] +
"']"
)
.parent()
.show();
}
}
}
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
},
});
});
Below is my JSON result:
{
"option": [
{
"product_option_id": "975",
"option_id": "76",
"name": "Stage",
"type": "image",
"option_value": [
{
"product_option_value_id": "2490",
"option_value_id": "389",
"name": "Level 1",
"price": "\u20ac 2,00"
},
{
"product_option_value_id": "2491",
"option_value_id": "390",
"name": "Level 2",
"price": "\u20ac 3,00"
}
],
"required": "1"
}
]
}
Thanks

I don't have an exact structure of your html, but atleast i can provide a clean solution with some Array.map usage.
You can loop through each object and then you can target HTML element you want to.
Example
result.option.map(opt => {
if (opt.type === 'radio' || opt.type === 'checkbox') {
let optionElement = '#ioption' + opt.option_id;
$(optionElement).find('input').prop('checked', false);
opt.option_value.map(optVal => {
let inputElement = 'input[value=\'' + optVal.product_option_value_id + '\']';
$(optionIdElement).find(inputElement).parent().show();
});
}
});
P.S: Snippet won't run as i've not included result json in the answer!
Hope this will help!

Get value of option_value use this option[0]["option_value"][0]
I just give answer according to display the top json.
And 0 replace using any loop(for / foreach) accoding to your requirment.

Related

how to get data from dynamic key pair value in Angular

here my issue i unable to get the dynamic key pair value from the dynamic json
below is my json
var d = {
"pexels-photo.jpeg": {
"information": "laptop",
"desc": {
"mimetype": "image/jpeg",
"id": "shsj44",
"file_id": "pexels-photo.jpeg"
},
"_id": "shsj44"
}
}
here i tried below
Object.keys(d).forEach(function(key){
var value = d[key];
console.log(key + ':' + value) ;
});
i want to get the id value "_id" & "file_id" values
You can use Destructuring assignment
var d = {"dynamic": {"information": "laptop","desc": { "mimetype": "image/jpeg","id": "shsj44","file_id": "pexels-photo.jpeg" },"_id": "shsj44"}}
let dynamicKey = Object.keys(d)[0]
let {[dynamicKey]:{desc:{
file_id
},_id}} = d
console.log(file_id, '\n', _id)
That is because of the + before the value, which will try to concatenate the value and you will see [object object]
var d = {
"pexels-photo.jpeg": {
"information": "laptop",
"desc": {
"mimetype": "image/jpeg",
"id": "shsj44",
"file_id": "pexels-photo.jpeg"
},
"_id": "shsj44"
}
}
Object.keys(d).forEach(function(key) {
let value = d[key];
console.log(key + ' : ', value);
console.log(key + ' : ', value.desc.id);
});
You need to check whether the value is object or not, if yes then you need to loop over it again.
Following code will print every key-value pair in d
export class AppComponent implements OnInit {
d = {
'pexels-photo.jpeg': {
'information': 'laptop',
'desc': {
'mimetype': 'image/jpeg',
'id': 'shsj44',
'file_id': 'pexels-photo.jpeg'
},
'_id': 'shsj44'
}
};
ngOnInit(): void {
this.calc(this.d);
}
calc(val) {
Object.keys(val).forEach(key => {
const value = val[key];
if (typeof (value) === 'object') {
this.calc(value);
} else {
console.log(key + ':' + value);
}
});
}
}
Try this :
var d = {
"pexels-photo.jpeg": {
"information": "laptop",
"desc": {
"mimetype": "image/jpeg",
"id": "shsj44",
"file_id": "pexels-photo.jpeg"
},
"_id": "shsj44"
}
};
Object.keys(d).filter(key => {
Object.keys(d[key]).filter(item => {
if (item === 'desc') {
Object.keys(d[key][item]).filter(elem => {
if ((elem === 'id') || (elem === 'file_id')) {
console.log(elem + ' : ' + d[key][item][elem]);
}
});
}
})
});

How can one iterate with this JSON response file

As said above, I don't know how to use this kind of JSON response from my server-side php which I got by using this code echo json_encode(array_merge($outp, $outp2));
[
{
"stuid":"12",
"stuname":"Velino Meratis",
"stucourse":"BSIT",
"stustat":"0",
"stulyear":"4",
"stulog":"feb 16 2017"
},
{
"stuid":"13",
"stuname":"Alana Melker",
"stucourse":"BSCE",
"stustat":"1",
"stulyear":"5",
"stulog":"feb 16 2017"
},
{
"stuid":"12",
"cname":"InfoTech000",
"clog":"1"
},
{
"stuid":"12",
"cname":"InfoTech001",
"clog":"2"
},
{
"stuid":"12",
"cname":"C101",
"clog":"3"
},
{
"stuid":"13",
"cname":"CE000",
"clog":"4"
},
{
"stuid":"13",
"cname":"CE001",
"clog":"5"
},
{
"stuid":"13",
"cname":"C101",
"clog":"6"
}
]
If I use this code in my client side javascript
if (this.readyState == 4 && this.status == 200) {
students = JSON.parse(this.responseText);
students.forEach(function(item){
console.log(item.stuid);
x = item.stuid;
document.getElementById("demo").innerHTML += x + " " + item.stuname + "<br>" + item.cname + "<br>";
});
}
it just ends up giving me this:-
12 Velino Meratis
undefined
13 Alana Melker
undefined
Somehow I can iterate the stuid and the stunamebut it won't allow them to contain the cname as an array with them.
How can I turn that into something like this:-
12 Velino Meratis
InfoTech000, InfoTech001, C101
13 Alana Melker
CE000, CE001, C101
Can someone Help and Elaborate on this?
You can check if the array contains the key or not, that way you will be saved from "undefined" error.
You can do it this way
if(item.hasOwnProperty('cname'))
{
console.log(item.cname);
}
You can use this for stuname or other keys also.
You need to merge student objects in your array by unique IDs. One way to do this is to add new stuids to an array and merge it with subsequent items with same stuid. Once you have array of unique students, you can proceed with other goals.
if (this.readyState == 4 && this.status == 200) {
var students_raw = JSON.parse(this.responseText);
var students = [];
students_raw.forEach(function(item){
var existing = students.find($item => item.stuid === $item.stuid);
if (existing) {
existing = Object.assign({}, existing, item);
} else {
students.push(item);
}
});
// your print loop
students.forEach(function(item) {
var x = item.stuid;
document.getElementById("demo").innerHTML += x + " " + item.stuname + "<br>" + item.cname + "<br>";
});
}
Please note: Array.reduce() and Object.assign() are not supported widely. you may need to polyfill these methods
NOTE: This answer assumes you're willing and able to change the data coming from PHP
Credit where credit is due, this is an extension of #Magnus Eriksson's comment.
It would be preferable to keep the relevant data associated with each other. You should get better flexibility with well-formed data. Ideally, you should do this server side and present the data to the client already well formatted.
You should try and achieve something similar to the following for your output:
[{
"stuid": "12",
"stuname": "Velino Meratis",
"stucourse": "BSIT",
"stustat": "0",
"stulyear": "4",
"stulog": "feb 16 2017",
"classes": [{
"cname": "InfoTech000",
"clog": "1"
}, {
"cname": "InfoTech001",
"clog": "2"
}, {
"cname": "C101",
"clog": "3"
}]
}, {
"stuid": "13",
"stuname": "Alana Melker",
"stucourse": "BSCE",
"stustat": "1",
"stulyear": "5",
"stulog": "feb 16 2017",
"classes": [{
"cname": "CE000",
"clog": "4"
}, {
"cname": "CE001",
"clog": "5"
}, {
"cname": "C101",
"clog": "6"
}]
}];
Note I've used classes as the property name as it appears we are working with Courses and their classes.
Your javascript will now look like:
if (this.readyState == 4 && this.status == 200) {
students = JSON.parse(this.responseText);
students.forEach(function(item){
console.log(item.stuid);
x = item.stuid;
document.getElementById("demo").innerHTML += x + " " + item.stuname + "<br>" + item.classes.map(function(elem){
return elem.cname;}).join(",") + "<br>";
});
}
Note the map function won't work in IE8 and lower.
Now for a working example:
var students = [{
"stuid": "12",
"stuname": "Velino Meratis",
"stucourse": "BSIT",
"stustat": "0",
"stulyear": "4",
"stulog": "feb 16 2017",
"classes": [{
"cname": "InfoTech000",
"clog": "1"
}, {
"cname": "InfoTech001",
"clog": "2"
}, {
"cname": "C101",
"clog": "3"
}]
}, {
"stuid": "13",
"stuname": "Alana Melker",
"stucourse": "BSCE",
"stustat": "1",
"stulyear": "5",
"stulog": "feb 16 2017",
"classes": [{
"cname": "CE000",
"clog": "4"
}, {
"cname": "CE001",
"clog": "5"
}, {
"cname": "C101",
"clog": "6"
}]
}];
students.forEach(function(item){
console.log(item.stuid);
x = item.stuid;
document.getElementById("demo").innerHTML += x + " " + item.stuname + "<br>" + item.classes.map(function(elem){
return elem.cname;}).join(",") + "<br>";
});
<div id="demo"></div>
As mentioned in other answers and comments, the issue with your existing code, is not all objects in your json array have the property you're referencing.
You can try like this once also
HTML
<div id="result"></div>
SCRIPT
var dataJSON = [
{
"stuid":"12",
"stuname":"Velino Meratis",
"stucourse":"BSIT",
"stustat":"0",
"stulyear":"4",
"stulog":"feb 16 2017"
},
{
"stuid":"13",
"stuname":"Alana Melker",
"stucourse":"BSCE",
"stustat":"1",
"stulyear":"5",
"stulog":"feb 16 2017"
},
{
"stuid":"12",
"cname":"InfoTech000",
"clog":"1"
},
{
"stuid":"12",
"cname":"InfoTech001",
"clog":"2"
},
{
"stuid":"12",
"cname":"C101",
"clog":"3"
},
{
"stuid":"13",
"cname":"CE000",
"clog":"4"
},
{
"stuid":"13",
"cname":"CE001",
"clog":"5"
},
{
"stuid":"13",
"cname":"C101",
"clog":"6"
}
] ;
var arr = {};
for(var i = 0 ; i< dataJSON.length ; i++){
var ele = dataJSON[i];
if(arr[ ele.stuid ]==undefined){
arr[ ele.stuid ] = {};
}
arr[ ele.stuid ]['stuid'] = ele.stuid;
if(ele.stuname!=undefined){
arr[ ele.stuid ]['stuname'] = ele.stuname;
}
if(arr[ ele.stuid ]['cname'] == undefined){
arr[ ele.stuid ]['cname'] = [];
}
if(ele.cname!=undefined){
arr[ ele.stuid ]['cname'].push(ele.cname);
}
}
var str = '';
for(var key in arr){
var obj = arr[key];
str += obj['stuid'] +" "+obj['stuname']+'<br/>';
str += obj['cname'].toString()+'<br/>';
}
document.getElementById("result").innerHTML = str;
Thanks,

Need assitance with matching JSON files

I am pretty new to JSON and JS and I am hoping someone can help me out. I am working with two separate JSON files. The recipe JSON file has an ID field and an ingredientNum field. In my second JSON file, I need to match the ingredientNum from the first JSON file with the corresponding field in the second JSON file called itemFullUPC. If there is a match in the fields, I need to replace the current ingredientNum that is displayed on the page in the unordered list with the itemName from the second JSON file that corresponds to the correct itemUPC. Below are the databases and my code. Hope someone can help me out!
Recipe JSON Example:
[
{
"recipeName":"Test",
"id":"10",
"ingredients":[
{
"ingredientNum":"070796501104",
"ingredientMeasure":"1 bottle",
"ingredientMisc1":"(33.8 fl oz)"
},
{
"ingredientNum":"070796000164",
"ingredientMeasure":"1/2 cup",
"ingredientMisc1":""
}
]
}
]
Product JSON Example:
[
{
"productName":"Tomatoes",
"itemFullUPC":"070796501104"
},
{
"productName":"Cherries",
"itemFullUPC":"070796000164"
}
]
For example, in the second database. The productName called "Cherries" has the same number in the first database, I need to replace the list that is currently generated on the page with the item names.
Expected Output
6-8 oz 070796501104 will become 6-8 oz Tomatoes
1/4 tsp 070796000164 will become 1-4 tsp Cherries
I need to do this for the whole list or anything the matches. I have included my attempt below thanks.
$(document).ready(function() {
'use strict';
$.ajax({
url: 'path to recipeDB',
cache: true,
success: function(data){
data = data.replace(/\\n/g, "\\n")
.replace(/\\'/g, "\\'")
.replace(/\\"/g, '\\"')
.replace(/\\&/g, "\\&")
.replace(/\\r/g, "\\r")
.replace(/\\t/g, "\\t")
.replace(/\\b/g, "\\b")
.replace(/\\f/g, "\\f");
data = data.replace(/[\u0000-\u0019]+/g,"");
var json = JSON.parse(data);
$.ajax({
dataType: "jsonp",
url: 'path to itemDB',
cache: true,
success: function(itemData){
var product_data = itemData;
var productUPC = '';
var productName = '';
$.each(product_data, function(i, item) {
productUPC += item.itemFullUPC;
productName += item.itemName;
});
var ingredients = '';
$.each(json, function(i, item) {
if (item.id == "10") {
ingredients += '<ul>';
for (var i = 0; i < item.ingredients.length; i++) {
ingredients += '<li>' + item.ingredients[i].ingredientMeasure + ' ' + item.ingredients[i].ingredientNum + ' ' + item.ingredients[i].ingredientMisc1 + '</li>';
}
ingredients += '</ul>';
}
});
$('#recipeIngredients').html(ingredients);
}
});
}
});
});
I successfully have the list working from the first database but I am not sure how to link to the second database and change the items from showing UPC in the list to the item name.
You can use Array.prototype.map() and Array.prototype.find()
var recipe = [{
"recipeName": "Test",
"id": "10",
"ingredients": [{
"ingredientNum": "070796501104",
"ingredientMeasure": "1 bottle",
"ingredientMisc1": "(33.8 fl oz)"
}, {
"ingredientNum": "070796000164",
"ingredientMeasure": "1/2 cup",
"ingredientMisc1": ""
}]
}];
var product = [{
"productName": "Tomatoes",
"itemFullUPC": "070796501104"
}, {
"productName": "Cherries",
"itemFullUPC": "070796000164"
}];
recipe.ingredients = recipe[0].ingredients.map(function(o) {
o.ingredientName = product.find(function(p) {
return p.itemFullUPC === o.ingredientNum;
}).productName;
return 0;
});
console.log(recipe);
The solution using Array.prototype.forEach() and Array.prototype.some() functions:
var recipes = [{"recipeName":"Test","id":"10","ingredients":[{"ingredientNum":"070796501104","ingredientMeasure":"1 bottle","ingredientMisc1":"(33.8 fl oz)"},{"ingredientNum":"070796000164","ingredientMeasure":"1/2 cup","ingredientMisc1":""}]}],
products = [{"productName":"Tomatoes","itemFullUPC":"070796501104"},{"productName":"Cherries","itemFullUPC":"070796000164"}];
recipes[0].ingredients.forEach(function (recipe) {
products.some(function (product) {
var cond = product.itemFullUPC === recipe.ingredientNum;
if (cond) {
recipe.ingredientNum = product.productName;
}
return cond;
});
});
console.log(recipes);
Now, you can iterate through the recipe ingredients and fill the unordered list
Assuming you have an array of recipes, you can remap the array like this:
var recipes = [{
"recipeName": "Test",
"id": "10",
"ingredients": [{
"ingredientNum": "070796501104",
"ingredientMeasure": "1 bottle",
"ingredientMisc1": "(33.8 fl oz)"
}, {
"ingredientNum": "070796000164",
"ingredientMeasure": "1/2 cup",
"ingredientMisc1": ""
}]
}]
var ingredients = [{
"productName": "Tomatoes",
"itemFullUPC": "070796501104"
}, {
"productName": "Cherries",
"itemFullUPC": "070796000164"
}]
recipes = recipes.map(function(recipe) {
return $.extend(recipe, {
ingredients: recipe.ingredients.map(function(ingr) {
return $.extend(ingr, {
productName: ingredients.find(function(el) {
return ingr.ingredientNum == el.itemFullUPC;
}).productName || ""
});
})
});
});
console.log(recipes);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I would change the products array over to an object so you do not have to keep looping over it to find the products. If you can change the server to return an object with keys instead of an array, that would be a bonus.
var recipe = [{
"recipeName": "Test",
"id": "10",
"ingredients": [{
"ingredientNum": "070796501104",
"ingredientMeasure": "1 bottle",
"ingredientMisc1": "(33.8 fl oz)"
}, {
"ingredientNum": "070796000164",
"ingredientMeasure": "1/2 cup",
"ingredientMisc1": ""
}]
}];
var products = [{
"productName": "Tomatoes",
"itemFullUPC": "070796501104"
}, {
"productName": "Cherries",
"itemFullUPC": "070796000164"
}];
//change products to object for easier lookup
var prodHash = products.reduce(function(o, item) {
o[item.itemFullUPC] = item.productName;
return o;
}, {});
var ingredients = recipe[0].ingredients.map(function(item) {
return "<li>" + item.ingredientMeasure + (item.ingredientMisc1.length ? " " + item.ingredientMisc1 + " " : " ") + prodHash[item.ingredientNum] + "</li>";
}).join("");
document.getElementById("out").innerHTML = ingredients;
<ul id="out"></ul>
first a sidenote:
//these don't do anything, you're literally replacing these strings with the very same strings
data = data.replace(/\\n/g, "\\n")
.replace(/\\'/g, "\\'")
.replace(/\\"/g, '\\"')
.replace(/\\&/g, "\\&")
.replace(/\\r/g, "\\r")
.replace(/\\t/g, "\\t")
.replace(/\\b/g, "\\b")
.replace(/\\f/g, "\\f");
//and these should usually not be in the JSON-string
data = data.replace(/[\u0000-\u0019]+/g, "");
so to the code:
$(document).ready(function() {
'use strict';
//first let's make the ajax-calls parallel
$.when(
$.ajax({
dataType: "jsonp",
url: 'path to recipeDB',
cache: true
}),
$.ajax({
dataType: "jsonp",
url: 'path to itemDB',
cache: true
})
).then(function(recipes, products){
//now let's convert the products into a more useful structure
var productsByUPC = products.reduce(function(acc, item){
acc[ item.itemFullUPC ] = item.productName;
return acc;
}, {});
//a sinple utility
//and don't be shy to use long and speaking names
//it's not your task to minify your code, it'the minifiers task
//and due to autocompletition one can not even brag about having to much to type
function formatIngredientAndAddName( ingredient ){
//here it makes no sense to add "ingredient" to each property name
//do you think, that `ingredient.ingredientMeasure`
//has any benefit over `ingredient.measure`
return {
name: productsByUPC[ ingredient.ingredientNum ],
measure: ingredient.ingredientMeasure,
misc: ingredient.ingredientMisc1
}
}
//and clean up the recipes
return recipes.map(function(recipe){
return {
id: recipe.id,
name: recipe.recipeName,
ingredients: recipe.ingredients.map( formatIngredientAndAddName )
}
});
}).then(function(recipes){
//now we have some clean data, containing all we need,
//let's create some markup
function ingredient2Markup(ingredient){
return '<li>'
+ ingredient.measure
+ ' '
+ ingredient.name
+ ' '
+ ingredient.misc1
+ '</li>';
}
function recipe2Markup(recipe){
return '<ul>' +
recipe.ingredients
.map( ingredient2Markup )
.join("")
+'</ul>';
}
$('#recipeIngredients').html(
recipes.map( recipe2Markup ).join("\n")
);
})
});
Edit:
the recipe data set is actually a php file that is formatted as an array so i cant use json p
I used jsonp there because the other request also was jsonp.
<?php
//... your php file
//json
$output = json_encode( $yourDataStructure );
$contentType = 'application/json';
//optional jsonp output
if(!empty( $_GET['callback'] )){
$contentType = 'application/javascript';
$output = $_GET['callback'] . '(' . $output . ')';
}
//setting the correct Content-Type
//and will throw if you already started sending something besides
header('Content-Type: ' . $contentType);
//ensure that this is the last/only thing that is sent to the client
exit( $output );
?>

How to iterate JSON Array in Jquery

I have this below type of array. I want to iterate this array in JavaScript. How is this possible?
{
"result": true,
"data": [
{
"ID": 1,
"stage_ID": 1,
"badge_type_ID": 1,
"name": "Despertar da Força",
"description": "Fazer a primeira SuperAtividade",
"type": "",
"image_static": "url123.jpg",
"image_animated": "",
"SQL": "",
"published": 1
},
{
"ID": 2,
"stage_ID": 1,
"badge_type_ID": 1,
"name": "Super 3",
"description": "Fazer 3 SuperAtividades",
"type": "",
"image_static": "urlimage123.png",
"image_animated": "",
"SQL": "",
"published": 1
}
etc
I tried the following script and it is returning "undefined", "undefined".
$.getJSON('https://www.legiaodossuperpoderes.com.br/chronus/api/adm/badges', function(data) {
var output= "<ol>";
for (var i in data) {
output += "<li>" + data[i].ID + "</li>"
}
output+="</ol>";
document.getElementById("placeholder").innerHTML=output;
});
Any solutions ? Thanks!
You can try converting to Json Object
$.getJSON('https://www.legiaodossuperpoderes.com.br/chronus/api/adm/badges', function(data) {
var output= "<ol>";
var jsondata = $.JSON.parse(data); // Json object Convertion
for (var i in data) {
output += "<li>" + data[i].ID + "</li>"
}
output+="</ol>";
document.getElementById("placeholder").innerHTML=output;
});
You are trying to access an undefined property using data[i].ID .
When you are getting response from your getJSON() function then you need to call the response with a name and then you can access any inner property using this name .
Now if you want to iterate using data key/value on myResponse variable then you need to do this.
$.getJSON('https://www.legiaodossuperpoderes.com.br/chronus/api/adm/badges', function(myResponse) {
var output= "<ol>";
var dataCount = myResponse.data.length;
for (var i = 0; i < dataCount; i++) {
output += "<li>" + myResponse.data[i].ID + "</li>";
}
output+="</ol>";
document.getElementById("placeholder").innerHTML=output;
});

Array data wont display in a table

I have an ajax function which sends a get request to an api and returns data in the following format-
{
"firstname": "John",
"lastname": "Doe",
"email": "doej#gmail.com",
"subjects": [
{
"id": 1,
"name": "maths"
},
{
"id": 2,
"name": "chemistry"
}
]
},
I need to display this data in a table but am having trouble getting the subjects array to display correctly, ie as a list in one table cell. I have tried to put the array data into another table inside the main one but it's not working out. I presume I'm going very wrong somewhere in my iteration loops.
function getPeople() {
$.ajax({
type: "GET",
url: "http://example.com",
contentType: "application/json; charset=utf-8",
crossDomain: true,
dataType: "json",
success: function (data, status, jqXHR) {
// fill a table with the JSON
$("table.mytable").html("<tr><th></th><th>First Name</th><th>Last Name</th><th>Subjects</th></tr>" );
for (var i = 0; i < data.length; i++) {
for (var j = 0; j < data[i].subjects.length; j++) {
var subjects = data[i].subjects[j];
$("table.insidetable").append('<tr><td>' + subjects + 'tr><td>')
}
$("table.mytable").append('<tr><td><input type = "checkbox" id = '+data[i].id+'>' + "</td><td>" + data[i].firstname + "</td><td>" + data[i].lastname + "</td><td>" + "table.insidetable" + "</td></tr>");
}
},
error: function (jqXHR, status) {
// error handler
console.log(jqXHR);
alert('fail' + status.code);
}
});
}
Below is the working (tested) code.
var data = [{
"firstname": "John",
"lastname": "Doe",
"email": "doej#gmail.com",
"subjects": [
{
"id": 1,
"name": "maths"
},
{
"id": 2,
"name": "chemistry"
}
]
},
{
"firstname": "Steve",
"lastname": "Gentile",
"email": "steve#gmail.com",
"subjects": [
{
"id": 1,
"name": "history"
},
{
"id": 2,
"name": "geography"
}
]
}];
$("table.mytable").html("<tr><th></th><th>First Name</th><th>Last Name</th><th>Subjects</th></tr>");
for (var i = 0; i < data.length; i++) {
var subjectList = '';
for (var j = 0; j < data[i].subjects.length; j++) {
subjectList += '<li>' + data[i].subjects[j].name + '</li>';
}
$("table.mytable").append('<tr><td><input type="checkbox" id=' + i +'/></td><td>' + data[i].firstname + '</td><td>' + data[i].lastname + '</td><td><ul>' + subjectList + '</ul></td></tr>');
}
It seems there are many problems in below statement like,
Tags are not closed properly
Properties that do not exist are being used (data[i].id)
Single and Double quotes don't match
...
$("table.mytable").append('<tr><td><input type = "checkbox" id = '+data[i].id+'>' + "</td><td>" +data[i].firstname + "</td><td>" + data[i].lastname + "</td><td>" + "table.insidetable"+ "</td></tr>");
As a guess are you missing a '<'?
In the line:
$("table.insidetable").append('<tr><td>' + subjects + 'tr><td>')
Also
$("table.mytable").append('<tr><td><input type = "checkbox" id = '+data[i].id+'>' + "</td><td>" + data[i].firstname + "</td><td>" + data[i].lastname + "</td><td>" + "table.insidetable" + "</td></tr>");
I don't think you should be appending "table.insidetable"? This will be seen rendered as the value "table.insidetable" and not the contents of the table. I think this should rather be something like $("table.insidetable").val()

Categories