Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I add for each grouped object new key value in javascript?

Hi all I have following array


    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
      },

    ];

I am trying to group array of objects in new array with following code

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

Output is

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Now how can I also add LineItemFile for each object ?

I want final result something like

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

Please help me resolve this.

I looked into this article but it not helped.

>Solution :

you can do something like 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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading