我有一个像这样的对象数组,
let employee = [
{
NodeType: "intern",
NodeName: "Node1"
}, {
NodeType: "intern",
NodeName: "Node2"
}, {
NodeType: "full-time",
NodeName: "Node1"
}, {
NodeType: "contract",
NodeName: "Node1"
}
]
我需要能够查看数组并查看所有员工是否全职然后返回“全职”或者如果员工名单只是“实习生”返回实习生或者如果其混合,则返回“混合”
我试过
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";
但有一种方法,我不会多次这样做,而是做一次
答案 0 :(得分:3)
将所有NodeType
值插入集合中,并检查大小。如果它超过1,则返回混合,如果不返回单个项目:
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)));