根据值过滤嵌套的对象属性 [英] Filter nested object properties based on value
问题描述
请考虑以下数据:
const state = {
tasks: {
'ID1': {
name: "Go to shop",
completed: false,
},
'ID2': {
name: "Get bananas",
completed: true,
},
'ID3': {
name: "Get apples",
completed: false,
}
}
}
要仅检索已将 completed
设置为 true
的任务,可以使用以下代码:
To retrieve only the tasks that have completed
set to true
the follwoing code can be used:
function getCompletedTasks(state) {
let tasks = {}
Object.keys(state.tasks).forEach((key) => {
let task = state.tasks[key]
if (task.completed) tasks[key] = task
})
return tasks
}
我想知道是否有比使用 let task = {}
手动创建新的 array
更好的方法?我看过 map
,但我不确定这是否有帮助.我是新手,只是想了解是否有更干净的更好的方法.
I was wondering if there's a better way than manually creating a new array
with let tasks = {}
? I've looked at map
but I'm not really sure this can help. I'm a newbie, just trying to understand if there's a cleaner better way.
推荐答案
您可以使用 Object.entries
获取条目数组,并根据值的是否已完成
属性是真实的,然后使用 Object.fromEntries
将其变成一个对象:
You can use Object.entries
to get an array of entries, filter it by whether the value's completed
property is truthy, then turn it back into an object with 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));
这篇关于根据值过滤嵌套的对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!