简体   繁体   中英

check for a property in array of objects and return a string based on the value

I have an array of objects like this ,

   let employee =  [
            {
                NodeType: "intern",
                NodeName: "Node1"
            }, {
                NodeType: "intern",
                NodeName: "Node2"
            }, {
                NodeType: "full-time",
                NodeName: "Node1"
            }, {
                NodeType: "contract",
                NodeName: "Node1"
            }
 ]

I need to be able to look through the array and see if all employees are full time then return "full time" or if the employee list is only "interns" return interns or if its mixed , return "mixed"

I tried

         var interntype = employee.find((obj) => {
                return obj.type == "intern" 
            });
         var fulltimetype = employee.find((obj) => {
                return obj.type == "full-time" 
            });
         var contracttype = employee.find((obj) => {
                return obj.type == "contract" 
            });

    if( internType) {
      return "intern";
    } else if (fulltimeType) {
          return "fullTime"
     } else return "mixed";

but is there a way where i dont do this multiple times and instead do it once

Insert all NodeType values into a set, and check the size. If it's more than 1, return mixed, if not return the single item:

 const employees = [{"NodeType":"intern","NodeName":"Node1"},{"NodeType":"intern","NodeName":"Node2"},{"NodeType":"full-time","NodeName":"Node1"},{"NodeType":"contract","NodeName":"Node1"}]; const getEmployeesType = (employees) => { const types = new Set(employees.map(({ NodeType }) => NodeType)); return types.size > 1 ? 'mixed' : [...types][0]; }; console.log('mixed: ', getEmployeesType(employees)); console.log('internes: ', getEmployeesType(employees.slice(0, 2))); 

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