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

JS中如何从嵌套对象数组结构中获取指定userName字段的值

你原来的写法存在两处错误:

  • example 本身是数组,不能直接通过 example.data 访问属性,需要先取到数组中的对象元素,比如 example[0]
  • filter 方法的作用是筛选符合条件的数组元素,你写的判断逻辑 item === item.userName 语义不成立,且语法上缺少闭合括号,无法实现提取字段的需求。

场景1:数据结构固定,外层数组和内部data数组都只有1个元素

直接按层级取值即可,代码最简单:

const userName = example[0].data[0].userName;
console.log(userName); // 输出 John Ferny

场景2:外层数组存在多个元素,要提取所有data内的userName值

用flatMap展开内部数组再映射取值:

const allUserNames = example.flatMap(outItem => {
  return outItem.data.map(inItem => inItem.userName)
});
// 得到所有userName组成的数组

场景3:需要按条件筛选特定的userName

用find方法筛选符合条件的元素再取值,避免取不到值报错:

// 示例:筛选id为793对应的userName
const targetItem = example[0].data.find(item => item.id === 793);
const userName = targetItem ? targetItem.userName : '';

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 23:45:03