考虑以下数据:const state = { tasks: { 'ID1': { name: "Go to shop", completed: false, }, 'ID2': { name: "Get bananas", completed: true, }, 'ID3': { name: "Get apples", completed: false, } }}要仅检索已completed设置为true以下代码的任务,可以使用:function getCompletedTasks(state) { let tasks = {} Object.keys(state.tasks).forEach((key) => { let task = state.tasks[key] if (task.completed) tasks[key] = task }) return tasks}我想知道是否有比手动创建新的更好的方法arraywith let tasks = {}?我看过,map但我不确定这会有所帮助。我是新手,只是想了解是否有更清洁的更好方法。
1 回答
哔哔one
TA贡献1854条经验 获得超8个赞
您可以使用Object.entries获取条目数组,根据值的completed属性是否为真对其进行过滤,然后将其转回具有以下内容的对象Object.fromEntries:
const state = {
tasks: {
'ID1': {
name: "Go to shop",
completed: false,
},
'ID2': {
name: "Get bananas",
completed: true,
},
'ID3': {
name: "Get apples",
completed: false,
}
}
}
function getCompletedTasks(state) {
return Object.fromEntries(
Object.entries(state.tasks).filter(([, val]) => val.completed)
);
}
console.log(getCompletedTasks(state));
添加回答
举报
0/150
提交
取消