【发布时间】:2021-03-03 02:12:52
【问题描述】:
我正在开发一个功能,我需要对一些项目进行分组并取消分组。
前几天我问了这个问题: How can I group specific items within an object in the same array and delete them from the core array? 有几个人帮我解决了分组问题。但这与这个问题非常相关。
我现在需要做的是按照完全相同的要求取消组合项目:取消组合 checked === true 组并将项目放回原处并删除所有重复项。
这是一个具有两种功能的可重现演示:https://codesandbox.io/s/ts-react-grouping-forked-rmwhr?file=/src/App.tsx
这里是相关的代码:
const handleUngroupingQuestions = (): void => {
const questionAddedCopy: VariableConfig[] = [...questionAdded]
const filteredByChecked: VariableConfig[] = questionAddedCopy.filter((q: VariableConfig) => isCheck.includes(q.id))
if (isCheck.length) {
setCheck([])
const extractGroup = (i: number): VariableConfig[] => filteredByChecked[i].questionGroup
const addChecked = (q: VariableConfig): VariableConfig => ({ ...q, questionGroup: [] })
// @TODO
// Remove this when we have a proper data structure
clearVariable()
const nestChecked = (qs: VariableConfig[], found = false) =>
qs.flatMap((q: VariableConfig, i: number) => {
if (filteredByChecked.includes(q)) {
if (found) {
return []
} else {
found = true
return [...[addChecked(q)], ...extractGroup(i)]
}
} else {
return [q]
}
})
const getNew = [...nestChecked(questionAdded)]
console.log({ getNew: JSON.stringify(getNew, null, 2) })
addQuestion(getNew.filter((g, i, a) => a.indexOf(g) === i))
}
}
由于某种原因,我现在收到一个错误:
Cannot read property 'questionGroup' of undefined
索引发生了一些事情。
所以我需要将所有项目与选中的属性分组为真。然后单击ungroup 并将项目带回其原始位置并删除当前组。即使有多组问题,我也必须能够做到这一点。
我错过了什么?
【问题讨论】:
标签: javascript arrays reactjs typescript ecmascript-6