简体   繁体   中英

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:

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 = {} ? 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.

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM