3 回答

TA貢獻1942條經驗 獲得超3個贊
正如評論:
這是 .filter().map() 有用的經典案例。過濾數據,然后使用 .map((o, i) => ({ ...obj, sequenceIndex: i+1 }) )
以下是示例:
const objectsArray = [{
folder: "folderName",
documents: [{
id: 0,
sequenceIndex: "0",
documentType: "letter"
},
{
id: 1,
sequenceIndex: "1",
documentType: "letter"
},
{
id: 2,
sequenceIndex: "2",
documentType: "letter"
},
{
id: 3,
sequenceIndex: "3",
documentType: "letter"
}
]
}];
const ignoreIds = [1, 2]
const updatedDocs = objectsArray[0].documents
.filter(({
id
}) => !ignoreIds.includes(id))
.map((doc, index) => ({ ...doc,
sequenceIndex: index
}));
console.log(updatedDocs)
現在讓我們介紹您的嘗試
const newObjArray = file.documents.map((obj: any) => {
// For all the unmatching objects, you will have undefined as object as you are using `.map`
// This will make you `newObjArray: Array<IDocument | undefined>` which can break your code.
if (obj.documentType === action.payload.documents[0].documentType) {
// This will set it as 0 in every iteration making i as 0 always.
let i = 0;
const correctedSequenceDocObject = { ...obj, sequenceIndex: i };
i++;
return correctedSequenceDocObject;
}
return { ...obj };
});
單循環的替代:
主意:
使用創建一個循環Array.reduce并將一個空白數組作為列表傳遞給它。
添加一個檢查并在其中將值推送到此列表。
對于sequenceIndex,獲取最后一個元素并獲取其sequenceIndex. 添加一個并重新設置。
const newObjArray = file.documents.reduce((acc: Array<IDocument>, obj: any) => {
if (obj.documentType === action.payload.documents[0].documentType) {
const sequenceIndex: number = (!!acc[acc.length - 1] ? acc[acc.length - 1].sequenceIndex : 1) + 1;
acc.push({ ...obj, sequenceIndex });
}
return acc;
});

TA貢獻1772條經驗 獲得超5個贊
你可以使用filter和map這樣的東西
const arr = [{folder: "folderName",documents: [{id: 0,sequenceIndex: "0",documentType: "letter"},{id: 1,sequenceIndex: "1",documentType: "letter"},{id: 2,sequenceIndex: "2",documentType: "letter"},{id: 3,sequenceIndex: "3",documentType: "letter"}]}];
let getInSequence = (filterId) => {
return arr[0].documents.filter(({ id }) => !filterId.includes(id))
.map((v, i) => ({ ...v, sequenceIndex: i }))
}
console.log(getInSequence([1, 2]))

TA貢獻1811條經驗 獲得超4個贊
我現在用來解決這個問題的解決方案是:
let count = 0;
const newObject = file.documents.map(obj => {
if (obj.documentType === firstDocument.documentType) {
count++;
return { ...obj, sequenceIndex: count - 1 };
}
return obj;
});
由于不同的 documentType,提供的兩個答案都無法處理不感興趣的對象,因此他們刪除了對象。使用此解決方案,我正在檢查最后一個元素并增加計數,如果最后一個元素是相同的 documentType。
添加回答
舉報