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。
添加回答
举报