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

如何修改JavaScript嵌套数组中多层对象的isFavorite属性值

问题排查
  • 直接错误原因:fruitAttributesChecked对应的map回调没有显式返回值,JavaScript函数无主动return时默认返回undefined,这是你得到[undefined, undefined]的核心原因。
  • 逻辑遗漏点:你没有把attributes.map生成的新数组挂载到新的水果对象上,即便补全return,也只会返回纯属性数组,丢失name、顶层isFavorite等字段,不符合预期结构。
  • 冗余逻辑:你不需要拆成两次map遍历,单次遍历即可同时完成顶层和嵌套属性的修改,减少性能消耗。
修正代码
const fruitAttributesChecked = fruits.map(fruit => {
  // 处理嵌套attributes数组的每个子项
  const newAttributes = fruit.attributes.map(attr => ({
    ...attr,
    isFavorite: true // 按需求全部设为true
  }))
  // 返回完整的新水果对象
  return {
    ...fruit,
    isFavorite: true,
    attributes: newAttributes
  }
})

如果你贴的预期输出是实际需要的效果(即保留attributes内原有isFavorite值,仅修改顶层isFavorite),只需要把内层map里的isFavorite: true改成isFavorite: attr.isFavorite即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 12:15:00