在 JS 中使用 map 合并嵌套数组

Merging nested array using map in JS

我正在通过这种方式从 Laravel API 获取数据

 $inventory = Gifts::with('allocation')->get();
 $response = [
   'data' => $inventory->toArray(),
 ]

上面的输出在控制台中如下图所示

这是 0 里面的内容:{…}

{
    "id": 1,
    "name": "Bar 1",
    "allocation": [
        {
            "id": 1,
            "location_id": "1",
            "qty": "2",
        },
        {
            "id": 2,
            "location_id": "4",
            "qty": "32",
        },
        {
            "id": 3,
            "location_id": "7",
            "qty": "12",
        }
    ]
}

我正在尝试获得这样的输出

{
    "isEditable": false,
    "id": 1,
    "name": "Bar 1",
    "location1": "2"
    "location4": "32"
    "location7": "12"
}

这是一个由 100 多个条目组成的数组,分配可以或多或少,也可以为空

到目前为止我做了什么

 const array = result.data(gift => ({ isEditable: false, ...gift }));

这会将“isEditable”字段添加到数组。

此解决方案使用 reduce

const { allocation, ...rest } = gift
const processed = allocation.reduce((acc, loc, idx) => {
  acc[`location${loc.location_id}`] = loc.qty
  return acc
}, {})
const result = { ...rest, ...processed }

console.log(result)

您可以使用 Array.prototype.map()result 数组映射到一个仅包含 idnamelocationNN 属性的新数组。

Array.prototype.map()的回调中:

  1. 使用扩展运算符将 allocation 属性 与每个数组项的其他属性分开(称之为 otherProps 例如):

  2. otherProps 展开到一个新对象中,插入 isEditable 属性.

  3. allocation项映射成键值对数组,其中键是location_id附加到"location";值是 qty 属性.

  4. 使用Object.fromEntries() on the key-value pair array to create an object, and spread that object进入要返回的外层对象

const output = result.map(r => {
  const { allocation, ...otherProps } = r 1️⃣
  return {
    ...otherProps, 2️⃣
    isEditable: false,
    ...Object.fromEntries( 4️⃣
      allocation.map(a => [`location${a.location_id}`, a.qty]) 3️⃣
    )
  }
})

demo