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

如何从数组对象中获取单个数值75000而非数组[75000]

获取单个price数值的实现方法

针对你现有代码中用map返回数组[75000],但需要单个数值75000的需求,提供以下几种实现方式:

原代码回顾

tickets = [
  {
    ticketCategories: {
      type: 'Presale 1 Ticket',
      price: 75000,
    },
    sumTicket: 3,
  },
];

let result = tickets.map(({ticketCategories}) => ticketCategories.price)
console.log(result); // 输出: [75000]

解决方案

1. 直接提取map返回数组的第一个元素

map会遍历数组所有元素并返回新数组,若你只需要第一个元素的price,直接取数组索引即可:

let result = tickets.map(({ticketCategories}) => ticketCategories.price)[0];
console.log(result); // 输出: 75000

也可以用ES6+的at()方法,写法更清晰:

let result = tickets.map(({ticketCategories}) => ticketCategories.price).at(0);

2. 直接访问数组元素的price(更高效)

如果确定tickets数组只有一个元素,没必要用map遍历,直接访问对应属性性能更好:

let result = tickets[0].ticketCategories.price;
console.log(result); // 输出: 75000

3. 用find定位目标对象后取price(适配多元素场景)

若数组可能包含多个元素,需要找到符合特定条件的对象再提取price,推荐用find:

// 示例:筛选type为"Presale 1 Ticket"的票种价格
let targetTicket = tickets.find(item => item.ticketCategories.type === 'Presale 1 Ticket');
// 可选链操作符`?.`避免找不到目标时抛出错误
let result = targetTicket?.ticketCategories.price;
console.log(result); // 输出: 75000

内容的提问来源于stack exchange,提问作者Eriy Suratman

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 14:05:22