Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

JavaScript filter nested objects by property value


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

1 Answer

0 votes
by (71.8m points)

filterList function will be called with the two params. categories - the list of categories, and keyword - search keyword. So my function checking each category from the category list. For each category, I filtered the children's list by the isHidden=false parameter and also by the existing profile with the name, which contains the keyword. I also using the toLocaleLowerCase function for the Case-insensitive. And if the category has a children's, which meet the requirements, I pushed to the result[], and overwrite the children value for it. And finally, the function returning the result array with required categories

const filterList = (categories, keyword) => {
  const kwd = keyword.toLocaleLowerCase()
  const result = [];
  for (const cat of categories) {
    const children = cat.children.filter(i => !i.isHidden && i.profiles.some(j => j.name.toLocaleLowerCase().includes(kwd)));
    if (children.length) result.push({ ...cat, children })
  }
  return result;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...