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

如何在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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 10:35:22