如何使用JavaScript从table1.data对象数组中提取电话值数组?
提取数组中所有对象的电话值
当然可以,用JavaScript的Array.prototype.map()方法就能轻松搞定,这是处理数组元素转换最常用的方法,很适合你的场景。
基础实现代码
const telephoneNumbers = table1.data.map(school => school.telephone);
代码说明
table1.data是你存储学校信息的对象数组map()会逐个遍历数组里的每个school对象- 每次遍历返回当前对象的
telephone属性值 - 执行完成后,
telephoneNumbers就是所有电话值组成的新数组
进阶:处理可能缺失的属性
如果数组里存在没有telephone属性的对象,为了避免结果出现undefined,可以加个简单判断:
// 缺失时用空字符串替代 const telephoneNumbers = table1.data.map(school => school.telephone || ''); // 更严谨的属性存在性判断 const telephoneNumbers = table1.data.map(school => school.hasOwnProperty('telephone') ? school.telephone : '' );
内容的提问来源于stack exchange,提问作者Macy Creed
相关产品推荐
相关产品推荐

