Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
230 views
in Technique[技术] by (71.8m points)

javascript - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...