3

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

    [ { 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.

3 Answers 3

5

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)

Sign up to request clarification or add additional context in comments.

Comments

1

Something like:


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


Comments

1

Try this :

const allFiles = arr.flatMap((obj) =>
    obj.ImageFileSet.flat().map((id) => ({
    ...id,
    LineItemFile: obj.LineItemFile
    }))
);

Output :

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.