如何将数组对象中嵌套的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
相关产品推荐
相关产品推荐

