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

如何从嵌套对象与数组的persons数组中提取所有siblings的firstName

问题原因

你的代码复用了外层循环的索引i访问内层siblings数组,导致只能拿到对应索引位置的单个siblings元素:

  • 外层遍历persons数组时i只能取0、1两个值
  • 第一个person的siblings只取到索引0的Jenny,漏掉Jim、Joe
  • 第二个person的siblings只取到索引1的Jose,漏掉George

解决方法

方法1:双层for循环(兼容旧写法)

新增单独的内层索引遍历siblings数组:

for(let i = 0; i < persons.length; i++){
  console.log(persons[i].firstName);
  // 内层遍历当前person的所有siblings
  let currentSiblings = persons[i].siblings;
  for(let j = 0; j < currentSiblings.length; j++){
    console.log(currentSiblings[j].firstName);
  }
}

运行后输出:

John
Jenny
Jim
Joe
Maria
George
Jose

方法2:现代JS写法(快速提取所有siblings的firstName)

如果只需要收集所有siblings的名字为数组,可以用flatMap组合map实现:

const allSiblingFirstNames = persons.flatMap(person => 
  person.siblings.map(item => item.firstName)
)
console.log(allSiblingFirstNames) // ["Jenny","Jim","Joe","George","Jose"]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 13:21:03