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(初始为空对象)逐步构建目标对象:- 取出当前字段的
attribute作为对象的键 - 取出当前字段的
value作为对应键的值 - 把键值对添加到累加器中,最后返回这个累加器作为
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
相关产品推荐
相关产品推荐

