Fire only once if key is found inside a JSON object











up vote
2
down vote

favorite












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
    2 days ago















up vote
2
down vote

favorite












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
    2 days ago













up vote
2
down vote

favorite









up vote
2
down vote

favorite











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 2 days ago









user13286

71951844




71951844








  • 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
    2 days ago














  • 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
    2 days ago








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
2 days ago




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
2 days ago












2 Answers
2






active

oldest

votes

















up vote
7
down vote



accepted










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






























    up vote
    1
    down vote













    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
      2 days ago












    • 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
      2 days ago












    • 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
      2 days ago











    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',
    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








    up vote
    7
    down vote



    accepted










    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



























      up vote
      7
      down vote



      accepted










      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

























        up vote
        7
        down vote



        accepted







        up vote
        7
        down vote



        accepted






        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 2 days ago

























        answered 2 days ago









        charlietfl

        137k1285118




        137k1285118
























            up vote
            1
            down vote













            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
              2 days ago












            • 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
              2 days ago












            • 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
              2 days ago















            up vote
            1
            down vote













            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
              2 days ago












            • 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
              2 days ago












            • 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
              2 days ago













            up vote
            1
            down vote










            up vote
            1
            down vote









            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 2 days ago









            Velimir Tchatchevsky

            2,02611117




            2,02611117








            • 1




              1. if (product.featured) 2. if (featured) 3. Array.some 4. exit the loop using return false;
              – Chris G
              2 days ago












            • 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
              2 days ago












            • 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
              2 days ago














            • 1




              1. if (product.featured) 2. if (featured) 3. Array.some 4. exit the loop using return false;
              – Chris G
              2 days ago












            • 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
              2 days ago












            • 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
              2 days ago








            1




            1




            1. if (product.featured) 2. if (featured) 3. Array.some 4. exit the loop using return false;
            – Chris G
            2 days ago






            1. if (product.featured) 2. if (featured) 3. Array.some 4. exit the loop using return false;
            – Chris G
            2 days ago














            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
            2 days ago






            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
            2 days ago














            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
            2 days ago




            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
            2 days ago


















             

            draft saved


            draft discarded



















































             


            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

            What visual should I use to simply compare current year value vs last year in Power BI desktop

            Alexandru Averescu

            Trompette piccolo