简体   繁体   中英

Create Set of objects from mongoose.find()

I need to create an object of filters based on unique values in my data to pass to my front-end application. I need one of the filters to be an array of objects. My previous method of [...new Set()] isn't working, I'm getting an error that says name: is unexpected, expected }

My other [...new Set()] functions all work as expected.

    let allEmployees = await db.Employee.find();

    let filters = {
      hiringManager: [...new Set(allEmployees.map(emp => {
         emplid: emp.emplid,
         name: emp.name,
         hrOrg: emp.hrOrg}
       ))].sort(function(a, b){return a.name - b.name}),
      countries:[...new Set(allEmployees.map(emp => emp.country))].sort(),
      globalGrades: [...new Set(allEmployees.map(emp => emp.globalGrade))].sort(),
      jobFamilies: [...new Set(allEmployees.map(emp => emp.jobFamily))].sort()
    };

Any ideas on how to return a Set of objects?

First, I would say to avoid using spread operator with Set. Because I got some interpretation issue sometimes in specific systems (spread operator was not good dealing with array-like).

 const allEmployees = [{ country: 'France', }, { country: 'Westeros', }, { country: 'France', }]; const unique = Array.from(new Set(allEmployees.map(emp => emp.country))).sort(); console.log(unique); 


Then in your case you miss a parenthesis. If you use map(emp => { like this, map will consider what is inside the { a function definition. If you want to return data directly from map, wrap it inside of () like :

map(() => ({

}));

 const allEmployees = [{ country: 'France', }, { country: 'Westeros', }, { country: 'France', }]; const ret = [ ...new Set(allEmployees.map(emp => ({ emplid: emp.country, }))), ]; console.log(ret); 

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