javascript - 如何在 javascript 中为每个分组对象添加新键值?

标签 javascript

大家好,我有以下数组


    const arr = [
      {
       ImageFileSet: [{ id: 1 }],
       LineItemFile: "new name",
       LineItemRef: "PDF",
       id: 44  
      },

       {
       ImageFileSet: [{ id: 7 }, { id: 8 }, { id: 9 }],
       LineItemFile: null,
       LineItemRef: "Image"
       id: 124
      },

    ];

我正在尝试使用以下代码对新数组中的对象数组进行分组

    const allFiles = arr .flatMap(({ ImageFileSet }) => [ImageFileSet]);

输出是

    [ { id: 1 }, { id: 7 }, { id: 8 }, { id: 9 } ]

现在我怎样才能为每个对象添加 LineItemFile

我想要类似的最终结果

    [ { id: 1,  LineItemFile: "new name", }, { id: 7,LineItemFile: null, }, { id: 8 , 
       LineItemFile: null,}, { id: 9 , LineItemFile: null,} ]

请帮我解决这个问题。

我查看了 this文章,但没有帮助。

最佳答案

你可以这样做

const arr = [{
    ImageFileSet: [{
      id: 1
    }],
    LineItemFile: "new name",
    LineItemRef: "PDF",
    id: 44
  },
  {
    ImageFileSet: [{
      id: 7
    }, {
      id: 8
    }, {
      id: 9
    }],
    LineItemFile: null,
    LineItemRef: "Image",
    id: 124
  },
];

const result = arr.flatMap(({ImageFileSet,LineItemFile}) =>
  ImageFileSet.map(d => ({ ...d, LineItemFile}))
)
console.log(result)

关于javascript - 如何在 javascript 中为每个分组对象添加新键值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72879398/

相关文章:

javascript - 如何修复 Bootstrap Carousel 'offSetWidth' 错误

javascript - NestJS、TypeORM,无法获取数据

javascript - 应用程序制作工具删除表中的项目并更新

javascript - Eventbug 的实际工作原理

JavaScript 正则表达式替换 : invalid quantifier

javascript - 将代码实现到现有站点的后台。 (用JS动画替换背景图片)

javascript - 如何在js对象中动态写入 key (作为函数的参数传递)?

javascript - HTML Canvas 绘图应用程序在不同的屏幕尺寸上中断

javascript - d3js - 在 exit() 转换后节点不会被删除

javascript - 迭代 li 元素,然后在某些 li 元素上添加 .addclass css