我正在尝试删除待办事项,我想从具有特定 ID 的对象“byIds”中删除该项目。 它将像数组的过滤器但对象的过滤器。 我不知道有什么这么复杂希望得到帮助我相信它很愚蠢
import { ADD_TODO, TOGGLE_TODO, DELETE_TODO } from "../actionTypes";
const initialState = {
allIds: [],
byIds: {},
};
export default function (state = initialState, action) {
switch (action.type) {
case ADD_TODO: {
const { id, content } = action.payload;
return {
...state,
allIds: [...state.allIds, id],
byIds: {
...state.byIds,
[id]: {
content,
completed: false,
},
},
};
}
case TOGGLE_TODO: {
const { id } = action.payload;
return {
...state,
byIds: {
...state.byIds,
[id]: {
...state.byIds[id],
completed: !state.byIds[id].completed,
},
},
};
}
// of course its toggling but it doesn't even get there
case DELETE_TODO: {
const { id } = action.payload;
return {
...state,
allIds: state.allIds.filter((todo) => todo !== id),
byIds: state.byIds.filter((todo) => todo !== id),
};
}
default:
return state;
}
}
{
todos: {
allIds: [
1,
2,
3,
4
],
byIds: {
'1': {
content: 'Test1',
completed: false
},
'2': {
content: 'Test2',
completed: false
},
'3': {
content: 'test3',
completed: false
},
'4': {
content: 'test4',
completed: false
}
}
},
visibilityFilter: 'all'
}
对于要求我控制台记录 byIds 的人,希望对我有所帮助
最佳答案
您需要的是遍历 byids
对象的 keys
并只取您需要的。
case DELETE_TODO: {
const { id } = action.payload;
let newObj = {}
Object.keys(state.byIds).forEach(function(key) {
if (key !== id) {
newObj[key] = state.byIds[key]
}
});
return {
...state,
allIds: state.allIds.filter((todo) => todo !== id),
byIds: newObj
};
}
如果您的 id 不是字符串而是数字,您需要检查 key != id
而不是 key !== id
关于javascript - 尝试对对象执行过滤方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63207563/