简体   繁体   中英

JavaScript Object loop - Filter and show duplicates once

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.

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))]); 

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

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; } } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM