如何用JavaScript将对象数组映射为仅含ground字段的新数组?
使用Array.map()提取对象数组的指定属性值
直接用Array.map()就能实现需求,不需要for循环或forEach:
完整代码示例
// 你的原始对象数组(简化了初始化写法,和原代码功能一致) const club = [ { team: "Manchester United", ground: "Old Trafford" }, { team: "Manchester City", ground: "Etihad" }, { team: "Liverpool", ground: "Anfield" } ]; // 提取所有ground属性值生成新数组 const search = club.map(item => item.ground); console.log(search); // 输出: ['Old Trafford', 'Etihad', 'Anfield']
核心逻辑说明
map()会遍历数组的每一个元素,对每个元素执行回调函数后,将返回值收集为新数组。- 这里的箭头函数
item => item.ground是简写形式,作用就是取出每个对象中的ground属性值作为新数组的元素。
内容的提问来源于stack exchange,提问作者London28
相关产品推荐
相关产品推荐

