我需要找到具有相同專案(ProjectID)的所有員工(EmpID),資料將是動態的,例如這個陣列。
[
{ EmpID: '143,', ProjectID: '12,', DateFrom: '2013-11-01,', DateTo: '2014-01-05\r' },
{ EmpID: '218,', ProjectID: '10,', DateFrom: '2012-05-16,', DateTo: 'NULL\r' },
{ EmpID: '143,', ProjectID: '10,', DateFrom: '2009-01-01,', DateTo: '2011-04-27' },
];
我希望這個陣列是 ->
[
{ EmpID: '218,', ProjectID: '10,', DateFrom: '2012-05-16,', DateTo: 'NULL\r' },
{ EmpID: '143,', ProjectID: '10,', DateFrom: '2009-01-01,', DateTo: '2011-04-27' },
];
uj5u.com熱心網友回復:
你應該能夠Array.reduce用來完成這個
// The "trick" is to pull out the first item and then use that as the match candidate
const [head, ...tail] = [{ EmpId: 1 }, { EmpId: 2 }, { EmpId: 1 }]
const output = tail.reduce(
(acc, b) => {
if (acc.map(o => o.EmpId).includes(b.EmpId)) {
acc.push(b)
}
return acc
},
[head]
)
uj5u.com熱心網友回復:
嘗試這樣的事情:
const projectEmployees = employees.filter( emp => emp.ProjectID === '12' );
有關Array.filter()血腥細節,請參閱。
或者...自己動手:
function selectEmployeesByProjectId( employees, id ) {
let projectEmployees = [];
for ( const emp of employees ) {
if ( emp.ProjectID === id ) {
projectEmployees.push(emp);
}
}
return projectEmployees;
}
如果您的資料確實是動態的,并且您不知道它的真實形狀,除了它是一個物件串列,只需讓您的函式靈活,如下所示。[但您仍然需要知道要匹配哪些屬性才能進行過濾。
function selectMatchingObjects( listOfObjects, isWanted ) {
return listOfObjects.filter( isWanted );
}
whereisWanted是一個函式,它接受一個物件,true如果要保留false該物件或要丟棄該物件,則回傳一個布林值。
一旦你有了它,你就可以做類似的事情
function selectEmployeesByProject( employees , projectIdKey , projectId ) {
const isWanted = emp = emp[projectIdKey] === projectId;
return employees.filter( isWanted );
}
進而
const employees = getMySomeDynamicEmployees();
. . .
const projectEmployees = selectEmployeesByProject(employees, 'ProjectId', '10');
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/370114.html
標籤:javascript 数组 筛选
