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

JavaScript遍历对象property并将嵌套array转为一维array

解决方案

核心逻辑很明确:先用递归函数扁平化任意深度的嵌套数组,再遍历原对象的所有属性,对每个属性值做扁平化处理,最后按要求生成对象数组。

1. 实现递归扁平化函数

这个函数能处理所有嵌套层级的数组,非数组输入会直接返回原值,兼容普通属性:

function flattenNestedArray(arr) {
  if (!Array.isArray(arr)) return arr;
  return arr.reduce((result, current) => {
    Array.isArray(current) 
      ? result.push(...flattenNestedArray(current)) 
      : result.push(current);
    return result;
  }, []);
}

2. 遍历对象生成目标数组

遍历原对象的每个属性,用上面的函数处理值,再将属性名和处理后的值包装成单个对象,最终组成数组:

function processObjectToArr(originalObj) {
  return Object.keys(originalObj).map(key => {
    const processedValue = flattenNestedArray(originalObj[key]);
    return { [key]: processedValue };
  });
}

3. 示例使用

假设原对象结构如下:

const product = {
  title: "Wireless Headphones",
  price: 99.99,
  main_image: "https://example.com/headphones-main.jpg",
  additional_images: [
    ["https://example.com/headphones-side.jpg"],
    ["https://example.com/headphones-charging.jpg", "https://example.com/headphones-box.jpg"]
  ]
};

调用函数后得到的结果:

const result = processObjectToArr(product);
console.log(result);
// 输出:
// [
//   { title: "Wireless Headphones" },
//   { price: 99.99 },
//   { main_image: "https://example.com/headphones-main.jpg" },
//   { additional_images: ["https://example.com/headphones-side.jpg", "https://example.com/headphones-charging.jpg", "https://example.com/headphones-box.jpg"] }
// ]

可选:生成单个处理后的对象

如果你的需求是生成一个所有嵌套数组都被扁平化的对象(而非对象数组),可以把map换成reduce:

function processObject(originalObj) {
  return Object.keys(originalObj).reduce((result, key) => {
    result[key] = flattenNestedArray(originalObj[key]);
    return result;
  }, {});
}

调用后会得到:

{
  title: "Wireless Headphones",
  price: 99.99,
  main_image: "https://example.com/headphones-main.jpg",
  additional_images: ["https://example.com/headphones-side.jpg", "https://example.com/headphones-charging.jpg", "https://example.com/headphones-box.jpg"]
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 03:15:49