Q:

forEach and map function to iterate through nested json arrays of objects and create a new array

var res=[
      {
         "id":1,
         "type_name":"Weight",
         "type_abbr":"wt",
         "uoms":[
            {
               "id":1,
               "unit_abbr":"sh tn",
               "unit_name":"Short Tons",
               "created_at":"2017-06-07 00:35:06",
               "updated_at":"2018-05-24 23:34:25",
               "uom_type_id":1
            },
            {
               "id":3,
               "unit_abbr":"g",
               "unit_name":"Grams",
               "created_at":"2017-06-07 00:35:06",
               "updated_at":"2018-05-24 23:34:25",
               "uom_type_id":1
            }
         ]
      }
   ]

I am trying to iterate through each result and grab the nested uoms.unit_name and inject them into a new array. Below is my non-working code. Thank you in advance.
res.forEach((uom) => {
  const uomsArr = uom.uoms.map(uoms => uoms.uoms);
});

A:

You can use reduce along with map:

var res = [{
    "id": 1,
    "type_name": "Weight",
    "type_abbr": "wt",
    "uoms": [{
        "id": 1,
        "unit_abbr": "sh tn",
        "unit_name": "Short Tons",
        "created_at": "2017-06-07 00:35:06",
        "updated_at": "2018-05-24 23:34:25",
        "uom_type_id": 1
      },
      {
        "id": 3,
        "unit_abbr": "g",
        "unit_name": "Grams",
        "created_at": "2017-06-07 00:35:06",
        "updated_at": "2018-05-24 23:34:25",
        "uom_type_id": 1
      }
    ]
  },
  {
    "id": 2,
    "type_name": "Weight",
    "type_abbr": "wt",
    "uoms": [{
        "id": 11,
        "unit_abbr": "sh tn",
        "unit_name": "Short Tons 2",
        "created_at": "2017-06-07 00:35:06",
        "updated_at": "2018-05-24 23:34:25",
        "uom_type_id": 11
      },
      {
        "id": 31,
        "unit_abbr": "g",
        "unit_name": "Grams 2",
        "created_at": "2017-06-07 00:35:06",
        "updated_at": "2018-05-24 23:34:25",
        "uom_type_id": 31
      }
    ]
  }
]

console.log(res.reduce((a, r) => [...a , ...r.uoms.map(u => u.unit_name)], []))

