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

如何在JavaScript中访问嵌套数组内的product对象?

访问嵌套数组内层元素的几种实用方法

直接索引访问

你的外层数组仅包含一个内层数组,可直接通过索引[0]获取内层数组,再通过索引访问具体元素的属性:

// 获取内层数组
const innerArray = arrayOfArrays[0];
console.log(innerArray); // 输出包含两个商品元素的数组

// 获取第一个元素的商品名称
const firstProductName = arrayOfArrays[0][0].product.name;
console.log(firstProductName); // 输出 "Product 1"

// 获取第二个元素的数量
const secondQuantity = arrayOfArrays[0][1].quantity;
console.log(secondQuantity); // 输出 2

遍历嵌套数组处理

如果外层数组可能包含多个内层数组,推荐用遍历方式批量处理元素:

for循环遍历

for (let outerIndex = 0; outerIndex < arrayOfArrays.length; outerIndex++) {
  const innerArr = arrayOfArrays[outerIndex];
  for (let innerIndex = 0; innerIndex < innerArr.length; innerIndex++) {
    const item = innerArr[innerIndex];
    console.log(`商品:${item.product.name},单价:${item.product.price},数量:${item.quantity}`);
  }
}

forEach方法遍历

arrayOfArrays.forEach(innerArr => {
  innerArr.forEach(item => {
    console.log(`商品:${item.product.name},单价:${item.product.price},数量:${item.quantity}`);
  });
});

扁平化数组后处理

用flat()方法将嵌套数组转为一维数组,简化后续操作:

const flattenedArray = arrayOfArrays.flat();
// 直接遍历一维数组
flattenedArray.forEach(item => {
  console.log(`商品:${item.product.name},单价:${item.product.price},数量:${item.quantity}`);
});

内容的提问来源于stack exchange,提问作者Md Adil

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 05:22:04