I want to filter the received json so that in html only the author's name and the quotation itself will go away. The error in the filter itself, but what I can not understand.

Code:

$(document).ready(function(){ $("#getMessage").on("click", function(){ //получаю json $.getJSON("http://quotes.stormconsultancy.co.uk/random.json", function(json) { var html = ""; //фильтр var filtered = json.filter(function(val){ return val.author && val.quote; }); //перебираю данные и вывожу в html $.each(filtered, function(key, val){ html += "<div class = 'quote'>"; html += "<p> author: " + key + "</p>" + "<p>" + val + "</p>"; html += "</div>"; }); $('.message').html(html); }); }); }); 

2 answers 2

In your example, everything is simple - the object is returned with one quote and there is no need to sort it through.

 $("#get-message").on("click", function(){ $.getJSON("http://quotes.stormconsultancy.co.uk/random.json", function(data) { $('#quote p').html('"' + data.quote + '" - ' + data.author); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="get-message">get-message</div> <div id="message"> <div id="quote"> <p></p> </div> </div> 

    Assuming the json parameter is an array:

      var html = ""; //фильтр var filtered = json.map(function(val){ return { author: val.author, quote: val.quote }; }); //перебираю данные и вывожу в html $.each(filtered, function(key, val){ html += "<div class = 'quote'>"; html += "<p> author: " + val.author + "</p>" + "<p>" + val.quote + "</p>"; html += "</div>"; }); $('.message').html(html); 
    • Somehow it makes no sense ... What prevents the initial array to immediately go $.each 'th and pull out what you need? I also understand that the author of the question does not really understand how and what works, but to do this in response is somehow wrong. - MedvedevDev