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

JS实现多维数组对象合并为一维数组对象

如何在JavaScript中将嵌套多维数组合并为一维数组对象

问题场景

现有一组嵌套数组,每个子数组仅包含一个对象:

[
  [{ propertyId: '3257', amenityId: '98' }],
  [{ propertyId: '3258', amenityId: '98' }],
  [{ propertyId: '3259', amenityId: '98' }],
  [{ propertyId: '3260', amenityId: '98' }],
  [{ propertyId: '3261', amenityId: '98' }],
  [{ propertyId: '3262', amenityId: '98' }],
  [{ propertyId: '3263', amenityId: '98' }],
  [{ propertyId: '3264', amenityId: '98' }],
  [{ propertyId: '3265', amenityId: '98' }],
  [{ propertyId: '3266', amenityId: '98' }]
]

需要将其合并为包含所有对象的一维数组:

[
  { propertyId: '3257', amenityId: '98' },
  { propertyId: '3258', amenityId: '98' },
  // ... 剩余对象
]

解决方案

方法1:使用Array.prototype.flat()(最简洁)

ES2019及以上版本支持的flat()方法可以直接扁平化数组,默认处理深度为1的嵌套,刚好适配当前场景:

const nestedArray = [
  [{ propertyId: '3257', amenityId: '98' }],
  [{ propertyId: '3258', amenityId: '98' }],
  // ... 其他元素
];

const flattenedArray = nestedArray.flat();
console.log(flattenedArray); // 输出期望的一维数组

方法2:使用Array.prototype.reduce()(兼容旧环境)

如果需要兼容不支持flat()的旧环境,可以用reduce()结合concat()实现:

const nestedArray = [
  [{ propertyId: '3257', amenityId: '98' }],
  [{ propertyId: '3258', amenityId: '98' }],
  // ... 其他元素
];

const flattenedArray = nestedArray.reduce((accumulator, currentItem) => {
  return accumulator.concat(currentItem);
}, []);
console.log(flattenedArray);

方法3:扩展运算符+forEach(直观易懂)

通过遍历每个子数组,用扩展运算符展开子数组元素并推入新数组:

const nestedArray = [
  [{ propertyId: '3257', amenityId: '98' }],
  [{ propertyId: '3258', amenityId: '98' }],
  // ... 其他元素
];

const flattenedArray = [];
nestedArray.forEach(subArr => {
  flattenedArray.push(...subArr);
});
console.log(flattenedArray);

内容的提问来源于stack exchange,提问作者Sok Chanty

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 19:31:15