I have problem understanding arrays and loops, therefore this task is a bit confusing to me. Here\'s my stuff;
JSON
{
\"states\": [
u can do it :
$(function(){
$.ajax({
type : 'GET',
url : 'scripts/list.json',
async : false,
beforeSend : function(){/*loading*/},
dataType : 'json',
success : function(result){
var buffer="";
$.each(result, function(index, val){
for(var i=0; i < val.length; i++){
var item = val[i];
console.log(item.name);
buffer+=" <li><a href='#"+item.name+"'>"+item.name+"</a></li> <li><a href='#"+item.command+"'>"+item.command+"</a></li>";
}
$('ul').html(buffer);
});
}
});
});
I'm checked this script and this works properly:
var records = {
"states": [
{
"name": "johor",
"command": "view_johor"
},
{
"name": "selangor",
"command": "view_selangor"
},
{
"name": "melaka",
"command": "view_melaka"
},
{
"name": "kuala lumpur",
"command": "view_kl"
},
{
"name": "penang",
"command": "view_penang"
}
]
};
$.each(records.states, function (key, val) {
$('#ul').append($('<li>').text('name: ' + val.name + ', command: ' + val.command));
});
and this is html:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<ul id="ul"></ul>
</body>
</html>
This should work :
Get the json file you want to read from, make a list of items using the key and values of the json data.And finally add the list inside a ul and append it to body.
$.getJSON( "jsonFile.json", function( data ) {
var items = [];
$.each( data, function( key, val1 ) {
$.each(val1, function(){
items.push( "<li><a href=#'" + this.command + "'>" + this.name + "</a></li>" );
});
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "body" );
});
Making very minor adjustments to your code,
var a = [];
$.each(result, function(index, val){
for(var i=0; i < val.length; i++){
var item = val[i];
a.push(item);
}
});
Now do something with all of the values in the array a
.
EDIT:
In case that wasn't enough,
var list = $('<ui></ui>');
$.each(result.states, function(state) {
var link = $('<a></a>').prop('href', state.command).text(state.name);
('<li></li>').append(link).appendTo(list);
});
list
is the HTML you want (except for the name capitalization...I wasn't sure if the first letter should be capitalized, or the first letter of each word, so I left that alone).
Jquery can create elements and append to your documents with few lines of code.
You can create an empty list like this.
var mylist=$("<ul></ul>");
Then inside your for
loop, for each item, do something like this
mylist.append($("<li></li>").text(item.name));
And finally append your newly built list to your document to get it displayed:
mylist.appendTo($("body"));