0

I have an object which has two arrays like:

let myData= {
        firstArray: [],
        seccondArray: []
};

firstArray is an Array which has some data with unique id's like:

firstArray = [
0: { id: 1, name: name1 },
1: { id: 2, name: name2 }
...]

seccondArray is another Array which has some data like:

seccondArray = [
0: { itemId: 1, nameForItem: name1, optionalProperty: property1 },
1: { itemId: 2, nameForItem: name2 },
2: { itemId: 3, nameForItem: name3 },
3: { itemId: 1, nameForItem: name4 }
...]

So I need to create finalArray which will have id and items array inside, where inside items will be pushed all items from seccondArray where the itemId = firstArray.id. id is the unique id taken firstArray.id. Also the element should be mapped with all its other properties like item1 has for example optionalProperty: property1, so finalArray looks like:

finalArray = [
{ id: 1, 
    items: [
      0: {itemId: 1, nameForItem: name1 , optionalProperty: property1}, 
      1: {itemId: 1, nameForItem: name4}
],},
{id: 2, items: [{itemId: 2, nameForItem: name2}]},
{id: 3, items: [{itemId: 3, nameForItem: name3}]},
{id: 4, items: [{itemId: 4, nameForItem: name4}]}
];
  • what goes wrong? – Nina Scholz Aug 21 '20 at 11:21
  • It seems array1 really serves no purpose. The result can be derived from array2 only. And such grouping questions have been asked before. – trincot Aug 21 '20 at 11:23
  • 1
    Welcome to Stack Overflow! Please take the [tour] (you get a badge!) and read through the [help], in particular [*How do I ask a good question?*](/help/how-to-ask) Your best bet here is to do your research, [search](/help/searching) for related topics on SO, and give it a go. ***If*** you get stuck and can't get unstuck after doing more research and searching, post a [mcve] of your attempt and say specifically where you're stuck. People will be glad to help. – T.J. Crowder Aug 21 '20 at 11:23

0 Answers0