Assuming I have the following object:
var results = {
itinerary:"01",
seats:[
{
rows:[
{
"seatNUmber": "A",
"IsAvailable": true
},
{
"seatNUmber": "B",
"IsAvailable": true
},
{
"seatNUmber": "C",
"IsAvailable": false
},
{
"seatNUmber": "D",
"IsAvailable": true
}
]
},
{
rows:[
{
"seatNUmber": "A",
"IsAvailable": true
},
{
"seatNUmber": "B",
"IsAvailable": true
},
{
"seatNUmber": "C",
"IsAvailable": false
},
{
"seatNUmber": "D",
"IsAvailable": true
}
]
}
]
}
So what I want to know is how can I parse this object into a table or a list, but dynamically create the components with jQuery?
Something like when parsing with AngularJS using ng-repeat
but in this case using jQuery.
You can read the object and generate HTML with jQuery. For example:
Here I leave a solution trying to be as faithful as possible (not always 100% possible) to the structure used in AngularJS.
The idea would be the following:
Use HTML5 attributes
data-*
to identify certain elements:data-init
. The value will be the name of the variable that contains the data.data-repeat
. The value will be the name of the array that contains the data to be displayed.data-value
. The value will be the name of the property within the object.Find the elements with the attribute
data-init
.data-repeat
.data-repeat
to avoid noise in the data (eg an empty row in a table).data-value
the value within the object specified indata-init
.So you could create simple HTML templates that would, using the case in the question as an example, look something like this:
And combine it with this (commented out) jQuery code to render that template:
Here is an example with the code above and the data from the question:
Advantages of this solution:
x in items
, but it would require more code).Disadvantages of this solution:
eval()
: which could create XSS and script injection problems if not used properly (eg: if the data being processed contains malicious code).The user asks the following: how can I parse this object into a table or a list, but dynamically creating the components with jQuery?
Assuming that the user wants to see which items are available from the value of each
IsAvailable
in a table. We can do the following:1- Indicate the title of the itinerary to be displayed.
2- Go through each of the rows of
seats
.3- Within each row print a cell for each of them and show their availability from
IsAvailable
.Here is the code, demonstrating what was explained above: