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

如何用JS的map方法合并Laravel API返回的嵌套数组实现数据扁平化

实现方案

直接通过数组map+reduce组合即可完成需求,完整代码如下:

const array = result.data.map(gift => {
  // 将allocation数组转换为 location+id 为键的扁平对象
  const locationMap = (gift.allocation ?? []).reduce((prev, curr) => {
    prev[`location${curr.location_id}`] = curr.qty;
    return prev;
  }, {});
  // 剔除原对象的allocation字段后合并所有属性
  const { allocation, ...baseFields } = gift;
  return {
    isEditable: false,
    ...baseFields,
    ...locationMap
  };
});

逻辑说明

  • 用gift.allocation ?? []做边界兼容,即使allocation为null/undefined/空数组也不会报错,会返回空的locationMap对象
  • reduce遍历allocation数组时动态拼接键名,把qty对应赋值,自动适配任意长度的allocation数组
  • 先解构剔除原gift中的allocation嵌套字段,再和isEditable、locationMap合并,最终得到符合要求的扁平结构
  • 性能层面,100+条数据的处理耗时可以忽略,完全满足日常使用需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 12:39:02