[英]Filter nested object properties based on value
Consider the following data:考虑以下数据:
const state = {
tasks: {
'ID1': {
name: "Go to shop",
completed: false,
},
'ID2': {
name: "Get bananas",
completed: true,
},
'ID3': {
name: "Get apples",
completed: false,
}
}
}
To retrieve only the tasks that have completed
set to true
the follwoing code can be used:要仅检索已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
}
I was wondering if there's a better way than manually creating a new array
with let tasks = {}
?我想知道是否有比使用let tasks = {}
手动创建新array
更好的方法? I've looked at map
but I'm not really sure this can help.我看过map
但我不确定这是否有帮助。 I'm a newbie, just trying to understand if there's a cleaner better way.我是新手,只是想了解是否有更清洁的更好方法。
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
:您可以使用Object.entries
获取条目数组,根据值的completed
属性是否真实进行过滤,然后使用 Z497031794414A552435F90151AC3B54 将其转回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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.