【问题标题】:How can I add for each grouped object new key value in javascript?如何在 javascript 中为每个分组对象添加新键值?
【发布时间】:2022-07-06 15:29:08
【问题描述】:

大家好,我有以下数组


    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 文章,但没有帮助。

【问题讨论】:

    标签: javascript


    【解决方案1】:

    你可以这样做

    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)

    【讨论】:

    • 感谢@R4ncid,它对我有用。
    【解决方案2】:

    类似:

    
        const allFiles = arr.flatMap((lineItem) => {
          return lineItem.ImageFileSet.map((imageFileSet) => (
              {...imageFileSet, LineItemFile: lineItem.LineItemFile}
            }))
       });
    
    
    

    【讨论】:

      猜你喜欢
      • 2013-09-28
      • 2019-02-02
      • 1970-01-01
      • 1970-01-01
      • 2019-04-03
      • 1970-01-01
      • 2021-07-17
      • 2019-08-27
      • 2020-11-30
      相关资源
      最近更新 更多