请考虑以下数据:
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
}
我想知道是否有比通过array
手动创建新的let tasks = {}
更好的方法?我看过map
,但我不确定这是否有帮助。我是新手,只是想了解是否有更清洁的更好方法。
答案 0 :(得分:1)
您可以使用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));