Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output Json Arrays with Javascript

I am really new to Javascript and Json and need help with the following. This is some json data:

"genres": [

 {
    "id": 28,
    "name": "Action"
 },
 {
    "id": 18,
    "name": "Drama"
 },
 {
    "id": 14,
    "name": "Fantasy"
 },
 {
    "id": 36,
    "name": "History"
 }

],

Now I would like to output all names of genres

I'm working with jquery mobile and ajax to retrieve json data. Inside my function it looks sth like this:

var genres = results.genres[0].name;
$('#tmdbInfo2').html('<br>Genres: ' +genres);

In this example the first element of genres will we shown (Action), but not all. The output should be: Action, Drama, Fantasy, History. Sometimes the number of elements of genres varies..

Please help me, its very confusing for me O_o

like image 224
RaveN Avatar asked Dec 01 '12 10:12

RaveN


People also ask

How do I post JSON data using JavaScript?

How do I post JSON data using JavaScript? To post data in JSON format using JavaScript/jQuery, you need to stringify your JavaScript object using the JSON. stringify() method and provide a Content-Type: application/json header with your request.

What is JSON array JavaScript?

A JSON array contains zero, one, or more ordered elements, separated by a comma. The JSON array is surrounded by square brackets [ ] . A JSON array is zero terminated, the first index of the array is zero (0). Therefore, the last index of the array is length - 1.

What is [] and {} in JSON?

' { } ' used for Object and ' [] ' is used for Array in json.


2 Answers

Plain Javascript

This is how you iterate on the elements of an array, using a for loop (do not use a for...in loop on arrays, if you ever get tempted).

for (var i = 0; i < results.genres.length; i++) {
    console.log( results.genres[i].name );
}

Your array is called results.genres here. Inside the loop, results.genres[i] will always refer to the current element.

jQuery

I see that you are using jQuery, so you can also use $.each() like this:

$.each(results.genres, function (currentIndex, currentElem) {
    console.log( currentElem.name );
});
like image 161
kapa Avatar answered Oct 21 '22 08:10

kapa


Another way to iterate:

results.genres.forEach(function(genre) {
    console.log(genre.name);
});

For what you're trying to do:

$('#tmdbInfo2').html(
    'Genres: ' + results.genres.map(function(genre) {
        return genre.name;
    }).join(', ')
);
like image 42
Eric Avatar answered Oct 21 '22 08:10

Eric