gpt4 book ai didi

javascript - 删除特定对象后,在数组中的对象中设置新序列

转载 作者:行者123 更新时间:2023-12-01 00:36:15 25 4
gpt4 key购买 nike

我的目标:我需要在sequenceIndex 中有一个连续的数字序列,它是我的对象中的一个值。

因此,当我删除特定对象时,其他对象的序列索引当然不再连续。我删除的对象正在根据特定值进行检查,以查看数组中是否有其他对象共享相同的值(第二个 if 语句)。如果是这样,那么应该有一个连续的新值集。

输出是 if 语句中的迭代器对于所有操作的对象始终相同。

从此:

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"
}
]
}
];

通过删除 id 1 和 2,我想得到这个(请参阅连续的序列索引):

const desiredObjectsArray = [
{
folder: "folderName",
documents: [
{
id: 0,
sequenceIndex: "0",
documentType: "letter"
},
{
id: 3,
sequenceIndex: "1",
documentType: "letter"
}
]
}
];

到目前为止我的代码:

case ActionType.RemoveDocumentInSpecificFolder:
return state.map(file => {
// if in the correct folder remove the object with the delivered id
if (file.folder=== folder) {
remove(file.documents, {
id: action.payload.documents[0].id
});

// create newObjArray from objects which share a specific value and replace the sequence index by new value
const newObjArray = file.documents.map((obj: any) => {
// if the object has the specific value create new object with new sequenceIndex
if (obj.documentType === action.payload.documents[0].documentType) {

//poor attempt to create a sequence
let i = 0;
const correctedSequenceDocObject = { ...obj, sequenceIndex: i };
i++;
return correctedSequenceDocObject;

}
return {
...obj
};
});
return {
...file,
documents: newObjArray
};
}
return file;
});

我希望有人能引导我走向正确的方向。我也总是很感激最佳实践的建议:)

致以诚挚的问候

最佳答案

您可以使用filtermap类似的东西

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]))

关于javascript - 删除特定对象后,在数组中的对象中设置新序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58111840/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com