JavaScript Object loop - Filter and show duplicates once












1















I have some code that works kind of like this:



var date = new Date();
var userMessage = {
UserName: "Charlie",
LastOnline: date.toDateString(),
Name: "Charlie"
};
Object.keys(userMessage).forEach(function(user) {
if (userMessage[user] == "Charlie") {
document.write("Welcome Charlie!");
}
});


However this works fine but i only would like the document to write "Welcome Charlie!" once. It will be possible that the user will have the same field twice, How would i limit this to once?



Soon this function will be wrapped with an angularJS ng-repeat. Maybe its possible to do this once with a filter?



Fiddle Link:
https://jsfiddle.net/dj5ka4g6/1/



Thanks.










share|improve this question

























  • Yeah exactly, But then if one of the messages had a reply i would only show a modal once rather than several times. I haven't created that yet and wanted to start with a different base.

    – MetalSlugSnk
    Nov 25 '18 at 23:48
















1















I have some code that works kind of like this:



var date = new Date();
var userMessage = {
UserName: "Charlie",
LastOnline: date.toDateString(),
Name: "Charlie"
};
Object.keys(userMessage).forEach(function(user) {
if (userMessage[user] == "Charlie") {
document.write("Welcome Charlie!");
}
});


However this works fine but i only would like the document to write "Welcome Charlie!" once. It will be possible that the user will have the same field twice, How would i limit this to once?



Soon this function will be wrapped with an angularJS ng-repeat. Maybe its possible to do this once with a filter?



Fiddle Link:
https://jsfiddle.net/dj5ka4g6/1/



Thanks.










share|improve this question

























  • Yeah exactly, But then if one of the messages had a reply i would only show a modal once rather than several times. I haven't created that yet and wanted to start with a different base.

    – MetalSlugSnk
    Nov 25 '18 at 23:48














1












1








1








I have some code that works kind of like this:



var date = new Date();
var userMessage = {
UserName: "Charlie",
LastOnline: date.toDateString(),
Name: "Charlie"
};
Object.keys(userMessage).forEach(function(user) {
if (userMessage[user] == "Charlie") {
document.write("Welcome Charlie!");
}
});


However this works fine but i only would like the document to write "Welcome Charlie!" once. It will be possible that the user will have the same field twice, How would i limit this to once?



Soon this function will be wrapped with an angularJS ng-repeat. Maybe its possible to do this once with a filter?



Fiddle Link:
https://jsfiddle.net/dj5ka4g6/1/



Thanks.










share|improve this question
















I have some code that works kind of like this:



var date = new Date();
var userMessage = {
UserName: "Charlie",
LastOnline: date.toDateString(),
Name: "Charlie"
};
Object.keys(userMessage).forEach(function(user) {
if (userMessage[user] == "Charlie") {
document.write("Welcome Charlie!");
}
});


However this works fine but i only would like the document to write "Welcome Charlie!" once. It will be possible that the user will have the same field twice, How would i limit this to once?



Soon this function will be wrapped with an angularJS ng-repeat. Maybe its possible to do this once with a filter?



Fiddle Link:
https://jsfiddle.net/dj5ka4g6/1/



Thanks.







javascript loops object






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 25 '18 at 23:42









Mark Meyer

39.3k33162




39.3k33162










asked Nov 25 '18 at 23:40









MetalSlugSnkMetalSlugSnk

235




235













  • Yeah exactly, But then if one of the messages had a reply i would only show a modal once rather than several times. I haven't created that yet and wanted to start with a different base.

    – MetalSlugSnk
    Nov 25 '18 at 23:48



















  • Yeah exactly, But then if one of the messages had a reply i would only show a modal once rather than several times. I haven't created that yet and wanted to start with a different base.

    – MetalSlugSnk
    Nov 25 '18 at 23:48

















Yeah exactly, But then if one of the messages had a reply i would only show a modal once rather than several times. I haven't created that yet and wanted to start with a different base.

– MetalSlugSnk
Nov 25 '18 at 23:48





Yeah exactly, But then if one of the messages had a reply i would only show a modal once rather than several times. I haven't created that yet and wanted to start with a different base.

– MetalSlugSnk
Nov 25 '18 at 23:48












3 Answers
3






active

oldest

votes


















0














One option would be to get the object's values with Object.values, deduplicate via a Set, and then iterate:






var date = new Date();
var userMessage = {
UserName: "Charlie",
LastOnline: date.toDateString(),
Name: "Charlie"
};

[...new Set(Object.values(userMessage))]
.forEach((val) => {
if (val === 'Charlie') console.log('Welcome Charlie');
});





Or, if, as your code seems to imply, you're just checking whether Charlie is included in the values, then use the .includes method:






var date = new Date();
var userMessage = {
UserName: "Charlie",
LastOnline: date.toDateString(),
Name: "Charlie"
};

if (Object.values(userMessage).includes('Charlie')) {
console.log('Welcome Charlie');
}





If you just need the deduplicated array, then:






var date = new Date();
var userMessage = {
UserName: "Charlie",
LastOnline: date.toDateString(),
Name: "Charlie"
};

console.log([...new Set(Object.values(userMessage))]);








share|improve this answer


























  • That's really nice! Looks like its what i need, How does the ellipses work? Never seen that kinda code before but it looks beautiful

    – MetalSlugSnk
    Nov 25 '18 at 23:46











  • It's called spread syntax, it's a bit nicer than concat, see MDN: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

    – CertainPerformance
    Nov 25 '18 at 23:47



















0














You can use .some to iterate until you find at least one good value:






var date = new Date();
var userMessage = {
UserName: "Charlie",
LastOnline: date.toDateString(),
Name: "Charlie"
};
Object.keys(userMessage).some(function(user) {
if (userMessage[user] == "Charlie") {
console.log("Welcome Charlie!");
return true;
}
});





https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some






share|improve this answer































    0














    Just use old for loop.






    const users = Object.keys(userMessage).map((key) => userMessage[key]);

    for (let i = 0; i < users.length; i++) {
    if (users[i] === 'Charlie') {
    console.log(`Welcome ${users[i]}`);
    break;
    }
    }








    share|improve this answer























      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%2f53473113%2fjavascript-object-loop-filter-and-show-duplicates-once%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      0














      One option would be to get the object's values with Object.values, deduplicate via a Set, and then iterate:






      var date = new Date();
      var userMessage = {
      UserName: "Charlie",
      LastOnline: date.toDateString(),
      Name: "Charlie"
      };

      [...new Set(Object.values(userMessage))]
      .forEach((val) => {
      if (val === 'Charlie') console.log('Welcome Charlie');
      });





      Or, if, as your code seems to imply, you're just checking whether Charlie is included in the values, then use the .includes method:






      var date = new Date();
      var userMessage = {
      UserName: "Charlie",
      LastOnline: date.toDateString(),
      Name: "Charlie"
      };

      if (Object.values(userMessage).includes('Charlie')) {
      console.log('Welcome Charlie');
      }





      If you just need the deduplicated array, then:






      var date = new Date();
      var userMessage = {
      UserName: "Charlie",
      LastOnline: date.toDateString(),
      Name: "Charlie"
      };

      console.log([...new Set(Object.values(userMessage))]);








      share|improve this answer


























      • That's really nice! Looks like its what i need, How does the ellipses work? Never seen that kinda code before but it looks beautiful

        – MetalSlugSnk
        Nov 25 '18 at 23:46











      • It's called spread syntax, it's a bit nicer than concat, see MDN: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

        – CertainPerformance
        Nov 25 '18 at 23:47
















      0














      One option would be to get the object's values with Object.values, deduplicate via a Set, and then iterate:






      var date = new Date();
      var userMessage = {
      UserName: "Charlie",
      LastOnline: date.toDateString(),
      Name: "Charlie"
      };

      [...new Set(Object.values(userMessage))]
      .forEach((val) => {
      if (val === 'Charlie') console.log('Welcome Charlie');
      });





      Or, if, as your code seems to imply, you're just checking whether Charlie is included in the values, then use the .includes method:






      var date = new Date();
      var userMessage = {
      UserName: "Charlie",
      LastOnline: date.toDateString(),
      Name: "Charlie"
      };

      if (Object.values(userMessage).includes('Charlie')) {
      console.log('Welcome Charlie');
      }





      If you just need the deduplicated array, then:






      var date = new Date();
      var userMessage = {
      UserName: "Charlie",
      LastOnline: date.toDateString(),
      Name: "Charlie"
      };

      console.log([...new Set(Object.values(userMessage))]);








      share|improve this answer


























      • That's really nice! Looks like its what i need, How does the ellipses work? Never seen that kinda code before but it looks beautiful

        – MetalSlugSnk
        Nov 25 '18 at 23:46











      • It's called spread syntax, it's a bit nicer than concat, see MDN: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

        – CertainPerformance
        Nov 25 '18 at 23:47














      0












      0








      0







      One option would be to get the object's values with Object.values, deduplicate via a Set, and then iterate:






      var date = new Date();
      var userMessage = {
      UserName: "Charlie",
      LastOnline: date.toDateString(),
      Name: "Charlie"
      };

      [...new Set(Object.values(userMessage))]
      .forEach((val) => {
      if (val === 'Charlie') console.log('Welcome Charlie');
      });





      Or, if, as your code seems to imply, you're just checking whether Charlie is included in the values, then use the .includes method:






      var date = new Date();
      var userMessage = {
      UserName: "Charlie",
      LastOnline: date.toDateString(),
      Name: "Charlie"
      };

      if (Object.values(userMessage).includes('Charlie')) {
      console.log('Welcome Charlie');
      }





      If you just need the deduplicated array, then:






      var date = new Date();
      var userMessage = {
      UserName: "Charlie",
      LastOnline: date.toDateString(),
      Name: "Charlie"
      };

      console.log([...new Set(Object.values(userMessage))]);








      share|improve this answer















      One option would be to get the object's values with Object.values, deduplicate via a Set, and then iterate:






      var date = new Date();
      var userMessage = {
      UserName: "Charlie",
      LastOnline: date.toDateString(),
      Name: "Charlie"
      };

      [...new Set(Object.values(userMessage))]
      .forEach((val) => {
      if (val === 'Charlie') console.log('Welcome Charlie');
      });





      Or, if, as your code seems to imply, you're just checking whether Charlie is included in the values, then use the .includes method:






      var date = new Date();
      var userMessage = {
      UserName: "Charlie",
      LastOnline: date.toDateString(),
      Name: "Charlie"
      };

      if (Object.values(userMessage).includes('Charlie')) {
      console.log('Welcome Charlie');
      }





      If you just need the deduplicated array, then:






      var date = new Date();
      var userMessage = {
      UserName: "Charlie",
      LastOnline: date.toDateString(),
      Name: "Charlie"
      };

      console.log([...new Set(Object.values(userMessage))]);








      var date = new Date();
      var userMessage = {
      UserName: "Charlie",
      LastOnline: date.toDateString(),
      Name: "Charlie"
      };

      [...new Set(Object.values(userMessage))]
      .forEach((val) => {
      if (val === 'Charlie') console.log('Welcome Charlie');
      });





      var date = new Date();
      var userMessage = {
      UserName: "Charlie",
      LastOnline: date.toDateString(),
      Name: "Charlie"
      };

      [...new Set(Object.values(userMessage))]
      .forEach((val) => {
      if (val === 'Charlie') console.log('Welcome Charlie');
      });





      var date = new Date();
      var userMessage = {
      UserName: "Charlie",
      LastOnline: date.toDateString(),
      Name: "Charlie"
      };

      if (Object.values(userMessage).includes('Charlie')) {
      console.log('Welcome Charlie');
      }





      var date = new Date();
      var userMessage = {
      UserName: "Charlie",
      LastOnline: date.toDateString(),
      Name: "Charlie"
      };

      if (Object.values(userMessage).includes('Charlie')) {
      console.log('Welcome Charlie');
      }





      var date = new Date();
      var userMessage = {
      UserName: "Charlie",
      LastOnline: date.toDateString(),
      Name: "Charlie"
      };

      console.log([...new Set(Object.values(userMessage))]);





      var date = new Date();
      var userMessage = {
      UserName: "Charlie",
      LastOnline: date.toDateString(),
      Name: "Charlie"
      };

      console.log([...new Set(Object.values(userMessage))]);






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Nov 25 '18 at 23:46

























      answered Nov 25 '18 at 23:43









      CertainPerformanceCertainPerformance

      94.3k165584




      94.3k165584













      • That's really nice! Looks like its what i need, How does the ellipses work? Never seen that kinda code before but it looks beautiful

        – MetalSlugSnk
        Nov 25 '18 at 23:46











      • It's called spread syntax, it's a bit nicer than concat, see MDN: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

        – CertainPerformance
        Nov 25 '18 at 23:47



















      • That's really nice! Looks like its what i need, How does the ellipses work? Never seen that kinda code before but it looks beautiful

        – MetalSlugSnk
        Nov 25 '18 at 23:46











      • It's called spread syntax, it's a bit nicer than concat, see MDN: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

        – CertainPerformance
        Nov 25 '18 at 23:47

















      That's really nice! Looks like its what i need, How does the ellipses work? Never seen that kinda code before but it looks beautiful

      – MetalSlugSnk
      Nov 25 '18 at 23:46





      That's really nice! Looks like its what i need, How does the ellipses work? Never seen that kinda code before but it looks beautiful

      – MetalSlugSnk
      Nov 25 '18 at 23:46













      It's called spread syntax, it's a bit nicer than concat, see MDN: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

      – CertainPerformance
      Nov 25 '18 at 23:47





      It's called spread syntax, it's a bit nicer than concat, see MDN: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

      – CertainPerformance
      Nov 25 '18 at 23:47













      0














      You can use .some to iterate until you find at least one good value:






      var date = new Date();
      var userMessage = {
      UserName: "Charlie",
      LastOnline: date.toDateString(),
      Name: "Charlie"
      };
      Object.keys(userMessage).some(function(user) {
      if (userMessage[user] == "Charlie") {
      console.log("Welcome Charlie!");
      return true;
      }
      });





      https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some






      share|improve this answer




























        0














        You can use .some to iterate until you find at least one good value:






        var date = new Date();
        var userMessage = {
        UserName: "Charlie",
        LastOnline: date.toDateString(),
        Name: "Charlie"
        };
        Object.keys(userMessage).some(function(user) {
        if (userMessage[user] == "Charlie") {
        console.log("Welcome Charlie!");
        return true;
        }
        });





        https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some






        share|improve this answer


























          0












          0








          0







          You can use .some to iterate until you find at least one good value:






          var date = new Date();
          var userMessage = {
          UserName: "Charlie",
          LastOnline: date.toDateString(),
          Name: "Charlie"
          };
          Object.keys(userMessage).some(function(user) {
          if (userMessage[user] == "Charlie") {
          console.log("Welcome Charlie!");
          return true;
          }
          });





          https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some






          share|improve this answer













          You can use .some to iterate until you find at least one good value:






          var date = new Date();
          var userMessage = {
          UserName: "Charlie",
          LastOnline: date.toDateString(),
          Name: "Charlie"
          };
          Object.keys(userMessage).some(function(user) {
          if (userMessage[user] == "Charlie") {
          console.log("Welcome Charlie!");
          return true;
          }
          });





          https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some






          var date = new Date();
          var userMessage = {
          UserName: "Charlie",
          LastOnline: date.toDateString(),
          Name: "Charlie"
          };
          Object.keys(userMessage).some(function(user) {
          if (userMessage[user] == "Charlie") {
          console.log("Welcome Charlie!");
          return true;
          }
          });





          var date = new Date();
          var userMessage = {
          UserName: "Charlie",
          LastOnline: date.toDateString(),
          Name: "Charlie"
          };
          Object.keys(userMessage).some(function(user) {
          if (userMessage[user] == "Charlie") {
          console.log("Welcome Charlie!");
          return true;
          }
          });






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 25 '18 at 23:44









          dotconnordotconnor

          1,180321




          1,180321























              0














              Just use old for loop.






              const users = Object.keys(userMessage).map((key) => userMessage[key]);

              for (let i = 0; i < users.length; i++) {
              if (users[i] === 'Charlie') {
              console.log(`Welcome ${users[i]}`);
              break;
              }
              }








              share|improve this answer




























                0














                Just use old for loop.






                const users = Object.keys(userMessage).map((key) => userMessage[key]);

                for (let i = 0; i < users.length; i++) {
                if (users[i] === 'Charlie') {
                console.log(`Welcome ${users[i]}`);
                break;
                }
                }








                share|improve this answer


























                  0












                  0








                  0







                  Just use old for loop.






                  const users = Object.keys(userMessage).map((key) => userMessage[key]);

                  for (let i = 0; i < users.length; i++) {
                  if (users[i] === 'Charlie') {
                  console.log(`Welcome ${users[i]}`);
                  break;
                  }
                  }








                  share|improve this answer













                  Just use old for loop.






                  const users = Object.keys(userMessage).map((key) => userMessage[key]);

                  for (let i = 0; i < users.length; i++) {
                  if (users[i] === 'Charlie') {
                  console.log(`Welcome ${users[i]}`);
                  break;
                  }
                  }








                  const users = Object.keys(userMessage).map((key) => userMessage[key]);

                  for (let i = 0; i < users.length; i++) {
                  if (users[i] === 'Charlie') {
                  console.log(`Welcome ${users[i]}`);
                  break;
                  }
                  }





                  const users = Object.keys(userMessage).map((key) => userMessage[key]);

                  for (let i = 0; i < users.length; i++) {
                  if (users[i] === 'Charlie') {
                  console.log(`Welcome ${users[i]}`);
                  break;
                  }
                  }






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 25 '18 at 23:56









                  ZiyoZiyo

                  26439




                  26439






























                      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%2f53473113%2fjavascript-object-loop-filter-and-show-duplicates-once%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

                      Ottavio Pratesi

                      Tricia Helfer

                      15 giugno