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

Vue项目中如何用JavaScript扁平化Laravel Nova返回的嵌套数组数据

解决嵌套数组对象的扁平化问题

这问题我太熟悉了!你需要的其实是把每条记录的字段数组转换成键值对对象,用map搭配reduce就能完美实现,比单独用map+filter更高效直接。

核心解决方案代码

直接上能解决你问题的代码:

const data = [
  [
    { attribute: 'id', value: 1, extra: "not needed data" },
    { attribute: 'title', value: 'The Title', extra: "not needed data" },
  ],
  [
    { attribute: 'id', value: 2 },
    { attribute: 'title', value: 'The Other Title' },
  ],
];

// 转换逻辑
const flattenedData = data.map(record => 
  record.reduce((acc, field) => {
    // 只提取attribute作为键,value作为值,自动忽略extra等冗余属性
    acc[field.attribute] = field.value;
    return acc;
  }, {}) // 初始累加器是一个空对象
);

console.log(flattenedData);
// 输出结果就是你想要的:
// [ {id: 1, title: 'The Title'}, {id: 2, title: 'The Other Title'} ]

代码逻辑拆解

  • 外层map:遍历原始数据中的每一条记录(也就是每个子数组),把每条记录转换成一个扁平对象。
  • 内层reduce:针对单条记录里的字段数组,用累加器acc(初始为空对象)逐步构建目标对象:
    1. 取出当前字段的attribute作为对象的键
    2. 取出当前字段的value作为对应键的值
    3. 把键值对添加到累加器中,最后返回这个累加器作为map的结果

进阶:过滤指定字段(可选)

如果担心后续API返回额外字段,想只保留明确需要的字段(比如id和title),可以加个过滤逻辑:

const allowedFields = ['id', 'title']; // 定义允许保留的字段

const flattenedData = data.map(record => 
  record.reduce((acc, field) => {
    if (allowedFields.includes(field.attribute)) {
      acc[field.attribute] = field.value;
    }
    return acc;
  }, {})
);

这样即使API返回了其他字段,也不会被混入最终的结果里,更安全。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 06:40:39