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

如何将数组对象中嵌套的students对象扁平化提取为studentName字段

实现方案

你可以直接使用数组的map遍历方法完成转换,以下是可直接运行的代码:

// 原接口返回的数组
const originArr = [
 {
  students: {id: '123456', name: 'Student Name'},
  active: true
 },
 {
  students: {id: '123456', name: 'Student Name'},
  active: true
 }
]

// 处理后的数组
const resultArr = originArr.map(item => {
  const { students, ...otherProps } = item
  return {
    studentName: students.name,
    ...otherProps
  }
})

如果需要兼容接口可能返回students为空的场景,避免读取name时报错,可以加上可选链和默认值容错:

const resultArr = originArr.map(item => {
  const { students, ...otherProps } = item
  return {
    studentName: students?.name ?? '', // students为空时默认赋值空字符串
    ...otherProps
  }
})

如果运行环境不支持ES6+语法,可以用普通循环实现:

var resultArr = []
for(var i = 0; i < originArr.length; i++) {
  var currentItem = originArr[i]
  resultArr.push({
    studentName: currentItem.students.name,
    active: currentItem.active
  })
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 18:39:03