Fire only once if key is found inside a JSON object












2















I have a JSON object of products. Within the object I want to check if any of the products have the featured key set to true. If the key exists anywhere within the object, I want to add an h3 above the results one single time.



Let's say I have an object with 4 products and one of those products has the featured key set to true, how would I adjust this code so that the h3 only gets added once(currently it's being added all 4 times)?



var searchResult = '';
$.each(products, function (id, product) {
if (products[id].featured) { searchResult += '<h3>Featured</h3>'; }
});









share|improve this question


















  • 3





    There's no such thing as a JSON object. You either have a string of JSON, or a JavaScript object (literal). As for your question: if (products.some(p => p.featured)) ...

    – Chris G
    Nov 21 '18 at 18:02
















2















I have a JSON object of products. Within the object I want to check if any of the products have the featured key set to true. If the key exists anywhere within the object, I want to add an h3 above the results one single time.



Let's say I have an object with 4 products and one of those products has the featured key set to true, how would I adjust this code so that the h3 only gets added once(currently it's being added all 4 times)?



var searchResult = '';
$.each(products, function (id, product) {
if (products[id].featured) { searchResult += '<h3>Featured</h3>'; }
});









share|improve this question


















  • 3





    There's no such thing as a JSON object. You either have a string of JSON, or a JavaScript object (literal). As for your question: if (products.some(p => p.featured)) ...

    – Chris G
    Nov 21 '18 at 18:02














2












2








2








I have a JSON object of products. Within the object I want to check if any of the products have the featured key set to true. If the key exists anywhere within the object, I want to add an h3 above the results one single time.



Let's say I have an object with 4 products and one of those products has the featured key set to true, how would I adjust this code so that the h3 only gets added once(currently it's being added all 4 times)?



var searchResult = '';
$.each(products, function (id, product) {
if (products[id].featured) { searchResult += '<h3>Featured</h3>'; }
});









share|improve this question














I have a JSON object of products. Within the object I want to check if any of the products have the featured key set to true. If the key exists anywhere within the object, I want to add an h3 above the results one single time.



Let's say I have an object with 4 products and one of those products has the featured key set to true, how would I adjust this code so that the h3 only gets added once(currently it's being added all 4 times)?



var searchResult = '';
$.each(products, function (id, product) {
if (products[id].featured) { searchResult += '<h3>Featured</h3>'; }
});






javascript json each






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 21 '18 at 18:00









user13286user13286

77251847




77251847








  • 3





    There's no such thing as a JSON object. You either have a string of JSON, or a JavaScript object (literal). As for your question: if (products.some(p => p.featured)) ...

    – Chris G
    Nov 21 '18 at 18:02














  • 3





    There's no such thing as a JSON object. You either have a string of JSON, or a JavaScript object (literal). As for your question: if (products.some(p => p.featured)) ...

    – Chris G
    Nov 21 '18 at 18:02








3




3





There's no such thing as a JSON object. You either have a string of JSON, or a JavaScript object (literal). As for your question: if (products.some(p => p.featured)) ...

– Chris G
Nov 21 '18 at 18:02





There's no such thing as a JSON object. You either have a string of JSON, or a JavaScript object (literal). As for your question: if (products.some(p => p.featured)) ...

– Chris G
Nov 21 '18 at 18:02












2 Answers
2






active

oldest

votes


















7














Add return false inside $.each callback to break the loop



var searchResult = '';
$.each(products, function (id, product) {
if (products[id].featured) {
searchResult += '<h3>Featured</h3>';
return false;
}
});


You could shorten this up a bit by using Array#find() or Array#some() instead



var searchResult = '';
var featured = products.some(function(prod){ return prod.featured});
if(featured){
searchResult += '<h3>Featured</h3>';
}





share|improve this answer

































    1














    Just have a variable to keep the featured state for you and modify it in the loop if there's a match



    var searchResult = '';
    var featured = false;
    $.each(products, function (id, product) {
    if (products[id].featured) { featured = true; }
    });

    if(featured === true){
    searchResult += '<h3>Featured</h3>';
    }





    share|improve this answer



















    • 1





      1. if (product.featured) 2. if (featured) 3. Array.some 4. exit the loop using return false;

      – Chris G
      Nov 21 '18 at 18:04













    • Seems unnecessary to continue looping through products after finding one that satisfies the criteria. If there are 1000 products and the first one is featured, you're doing 999 iterations too many.

      – Tyler Roper
      Nov 21 '18 at 18:04













    • If that's the only purpose of the function yes. But I can image OP using a loop already to go through all the elements and just wanting to add the extra functionality to it. That's the situation this answer would be helpful, otherwise @charlietfl's answer would be better.

      – Velimir Tchatchevsky
      Nov 21 '18 at 18:12











    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53418051%2ffire-only-once-if-key-is-found-inside-a-json-object%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    7














    Add return false inside $.each callback to break the loop



    var searchResult = '';
    $.each(products, function (id, product) {
    if (products[id].featured) {
    searchResult += '<h3>Featured</h3>';
    return false;
    }
    });


    You could shorten this up a bit by using Array#find() or Array#some() instead



    var searchResult = '';
    var featured = products.some(function(prod){ return prod.featured});
    if(featured){
    searchResult += '<h3>Featured</h3>';
    }





    share|improve this answer






























      7














      Add return false inside $.each callback to break the loop



      var searchResult = '';
      $.each(products, function (id, product) {
      if (products[id].featured) {
      searchResult += '<h3>Featured</h3>';
      return false;
      }
      });


      You could shorten this up a bit by using Array#find() or Array#some() instead



      var searchResult = '';
      var featured = products.some(function(prod){ return prod.featured});
      if(featured){
      searchResult += '<h3>Featured</h3>';
      }





      share|improve this answer




























        7












        7








        7







        Add return false inside $.each callback to break the loop



        var searchResult = '';
        $.each(products, function (id, product) {
        if (products[id].featured) {
        searchResult += '<h3>Featured</h3>';
        return false;
        }
        });


        You could shorten this up a bit by using Array#find() or Array#some() instead



        var searchResult = '';
        var featured = products.some(function(prod){ return prod.featured});
        if(featured){
        searchResult += '<h3>Featured</h3>';
        }





        share|improve this answer















        Add return false inside $.each callback to break the loop



        var searchResult = '';
        $.each(products, function (id, product) {
        if (products[id].featured) {
        searchResult += '<h3>Featured</h3>';
        return false;
        }
        });


        You could shorten this up a bit by using Array#find() or Array#some() instead



        var searchResult = '';
        var featured = products.some(function(prod){ return prod.featured});
        if(featured){
        searchResult += '<h3>Featured</h3>';
        }






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 21 '18 at 18:13

























        answered Nov 21 '18 at 18:05









        charlietflcharlietfl

        139k1389122




        139k1389122

























            1














            Just have a variable to keep the featured state for you and modify it in the loop if there's a match



            var searchResult = '';
            var featured = false;
            $.each(products, function (id, product) {
            if (products[id].featured) { featured = true; }
            });

            if(featured === true){
            searchResult += '<h3>Featured</h3>';
            }





            share|improve this answer



















            • 1





              1. if (product.featured) 2. if (featured) 3. Array.some 4. exit the loop using return false;

              – Chris G
              Nov 21 '18 at 18:04













            • Seems unnecessary to continue looping through products after finding one that satisfies the criteria. If there are 1000 products and the first one is featured, you're doing 999 iterations too many.

              – Tyler Roper
              Nov 21 '18 at 18:04













            • If that's the only purpose of the function yes. But I can image OP using a loop already to go through all the elements and just wanting to add the extra functionality to it. That's the situation this answer would be helpful, otherwise @charlietfl's answer would be better.

              – Velimir Tchatchevsky
              Nov 21 '18 at 18:12
















            1














            Just have a variable to keep the featured state for you and modify it in the loop if there's a match



            var searchResult = '';
            var featured = false;
            $.each(products, function (id, product) {
            if (products[id].featured) { featured = true; }
            });

            if(featured === true){
            searchResult += '<h3>Featured</h3>';
            }





            share|improve this answer



















            • 1





              1. if (product.featured) 2. if (featured) 3. Array.some 4. exit the loop using return false;

              – Chris G
              Nov 21 '18 at 18:04













            • Seems unnecessary to continue looping through products after finding one that satisfies the criteria. If there are 1000 products and the first one is featured, you're doing 999 iterations too many.

              – Tyler Roper
              Nov 21 '18 at 18:04













            • If that's the only purpose of the function yes. But I can image OP using a loop already to go through all the elements and just wanting to add the extra functionality to it. That's the situation this answer would be helpful, otherwise @charlietfl's answer would be better.

              – Velimir Tchatchevsky
              Nov 21 '18 at 18:12














            1












            1








            1







            Just have a variable to keep the featured state for you and modify it in the loop if there's a match



            var searchResult = '';
            var featured = false;
            $.each(products, function (id, product) {
            if (products[id].featured) { featured = true; }
            });

            if(featured === true){
            searchResult += '<h3>Featured</h3>';
            }





            share|improve this answer













            Just have a variable to keep the featured state for you and modify it in the loop if there's a match



            var searchResult = '';
            var featured = false;
            $.each(products, function (id, product) {
            if (products[id].featured) { featured = true; }
            });

            if(featured === true){
            searchResult += '<h3>Featured</h3>';
            }






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 21 '18 at 18:03









            Velimir TchatchevskyVelimir Tchatchevsky

            2,17411118




            2,17411118








            • 1





              1. if (product.featured) 2. if (featured) 3. Array.some 4. exit the loop using return false;

              – Chris G
              Nov 21 '18 at 18:04













            • Seems unnecessary to continue looping through products after finding one that satisfies the criteria. If there are 1000 products and the first one is featured, you're doing 999 iterations too many.

              – Tyler Roper
              Nov 21 '18 at 18:04













            • If that's the only purpose of the function yes. But I can image OP using a loop already to go through all the elements and just wanting to add the extra functionality to it. That's the situation this answer would be helpful, otherwise @charlietfl's answer would be better.

              – Velimir Tchatchevsky
              Nov 21 '18 at 18:12














            • 1





              1. if (product.featured) 2. if (featured) 3. Array.some 4. exit the loop using return false;

              – Chris G
              Nov 21 '18 at 18:04













            • Seems unnecessary to continue looping through products after finding one that satisfies the criteria. If there are 1000 products and the first one is featured, you're doing 999 iterations too many.

              – Tyler Roper
              Nov 21 '18 at 18:04













            • If that's the only purpose of the function yes. But I can image OP using a loop already to go through all the elements and just wanting to add the extra functionality to it. That's the situation this answer would be helpful, otherwise @charlietfl's answer would be better.

              – Velimir Tchatchevsky
              Nov 21 '18 at 18:12








            1




            1





            1. if (product.featured) 2. if (featured) 3. Array.some 4. exit the loop using return false;

            – Chris G
            Nov 21 '18 at 18:04







            1. if (product.featured) 2. if (featured) 3. Array.some 4. exit the loop using return false;

            – Chris G
            Nov 21 '18 at 18:04















            Seems unnecessary to continue looping through products after finding one that satisfies the criteria. If there are 1000 products and the first one is featured, you're doing 999 iterations too many.

            – Tyler Roper
            Nov 21 '18 at 18:04







            Seems unnecessary to continue looping through products after finding one that satisfies the criteria. If there are 1000 products and the first one is featured, you're doing 999 iterations too many.

            – Tyler Roper
            Nov 21 '18 at 18:04















            If that's the only purpose of the function yes. But I can image OP using a loop already to go through all the elements and just wanting to add the extra functionality to it. That's the situation this answer would be helpful, otherwise @charlietfl's answer would be better.

            – Velimir Tchatchevsky
            Nov 21 '18 at 18:12





            If that's the only purpose of the function yes. But I can image OP using a loop already to go through all the elements and just wanting to add the extra functionality to it. That's the situation this answer would be helpful, otherwise @charlietfl's answer would be better.

            – Velimir Tchatchevsky
            Nov 21 '18 at 18:12


















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53418051%2ffire-only-once-if-key-is-found-inside-a-json-object%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            MongoDB - Not Authorized To Execute Command

            How to fix TextFormField cause rebuild widget in Flutter

            in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith