如何在JavaScript中从对象数组获取所有age值?
获取对象数组中的所有age值
下面是几种常用的实现方式:
方法1:使用map()方法
map()是最简洁的方式,它会遍历数组并返回由每个对象的age属性组成的新数组:
const data = [{"hello":'thameem',"age":24},{"hello":'thameem',"age":25}]; const ages = data.map(item => item.age); console.log(ages); // 输出: [24, 25]
方法2:使用forEach()方法
如果需要手动控制收集过程,可以用forEach()遍历数组,将每个age值推入新数组:
const data = [{"hello":'thameem',"age":24},{"hello":'thameem',"age":25}]; const ages = []; data.forEach(item => ages.push(item.age)); console.log(ages); // 输出: [24, 25]
方法3:使用for...of循环
传统的for...of循环也能轻松实现需求:
const data = [{"hello":'thameem',"age":24},{"hello":'thameem',"age":25}]; const ages = []; for (const item of data) { ages.push(item.age); } console.log(ages); // 输出: [24, 25]
内容的提问来源于stack exchange,提问作者Loyalty_Thameem
相关产品推荐
相关产品推荐

