You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于categoriesElements为categories数组添加edit、browse全局校验属性

实现代码

首先先对分类元素按field字段做分组,避免重复遍历提升性能,再遍历分类数组计算属性值即可:

// 先将分类元素按field分组
const elementsByField = categoriesElements.reduce((acc, item) => {
  if (!acc[item.field]) acc[item.field] = []
  acc[item.field].push(item)
  return acc
}, {})

// 遍历分类数组新增属性,不修改原数组的写法
const processedCategories = categories.map(category => {
  const currentElements = elementsByField[category.field] ?? []
  // 无匹配元素时默认返回false,可根据需求调整默认值
  const allEditTrue = currentElements.length ? currentElements.every(el => el.edit) : false
  const allBrowseTrue = currentElements.length ? currentElements.every(el => el.browse) : false
  return {
    ...category,
    edit: allEditTrue,
    browse: allBrowseTrue
  }
})

// 如果需要直接修改原categories数组,用下面的写法代替map即可
// categories.forEach(category => {
//   const currentElements = elementsByField[category.field] ?? []
//   category.edit = currentElements.length ? currentElements.every(el => el.edit) : false
//   category.browse = currentElements.length ? currentElements.every(el => el.browse) : false
// })

注意事项

  • 你提供的示例代码中categoriesElements数组里的browse true存在语法错误,需要修改为browse: true才能正常运行
  • 若分类没有匹配的categoriesElements元素,默认返回false,如果你的业务需求是无匹配元素时默认设为true,修改三元表达式的默认返回值即可
  • 按你给出的示例数据运行后:
    • field为tags的分类,edit和browse属性均为true
    • field为retargeting_pixels、dashboard的分类,无匹配元素,edit和browse均为默认的false

内容的提问来源于stack exchange,提问作者R3muald

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 06:48:00