Home > database >  ForEach inside Foreach Javascript
ForEach inside Foreach Javascript

Time:04-20

Hi how do I loop trough an array i already looped trough? So i foreach the subarray and still having the the old array

array =  [
{
"DocNum": 210446, 
"DocType": "Test",
"DocumentLines": [
{
"LineNum": 0,
"ItemCode": "427"
}, 
{
"LineNum": 0,
"ItemCode": "34"
}
]
},
{
"DocNum": 210446, 
"DocType": "Test",
 "DocumentLines": [
{
  "LineNum": 0,
  "ItemCode": "427"
  }, 
  {
    "LineNum": 0,
    "ItemCode": "34"
    }
  ]
  }
 ]

for (let element of array) {
 newArray.push({
    key1: element.DocNum,
    key2: element.DocType,
    key3: element.DocumentLines[???].ItemCode
})}

So the array will look like this in the end

{ "key1":210446, "key2":Test, "key3": [{ItemCode: 34},{"ItemCode": 427}] }

CodePudding user response:

You can map the itemCodes

element.DocumentLines.map(v => v.ItemCode)

This will return the array of ItemCodes from your first array.

  • Related